<?php /* Smarty version 2.6.20, created on 2013-05-30 02:40:15
         compiled from _core/_include/common/dlmanageutils.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('modifier', 'escape', '_core/_include/common/dlmanageutils.tpl', 11, false),)), $this); ?>
﻿function DlmanageUtils() {
};

DlmanageUtils.number = 20;

DlmanageUtils.normal = 1;
DlmanageUtils.dop = 2;
DlmanageUtils.mixed = 3;
DlmanageUtils.none = 4;

DlmanageUtils.sqlPrecon = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRECON)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlMusic = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_MUSIC)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlRequirement = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_REQUIREMENT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlPhotographer = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_USER_PHOTOGRAPHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlVideographer = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_USER_VIDEOGRAPHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlMakeup = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_USER_MAKEUP)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlLight = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_USER_LIGHT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlProduct4x6 = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_4X6)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlProductRetouch = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_RETOUCH)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlProductRetouchMagazine = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_RETOUCH_MAGAZINE)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlProductCommon = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_COMMON)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlProductVideo = '(d.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_VIDEO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\')';
DlmanageUtils.sqlProductVideoB = '(d.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_VIDEO_BLURAY)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\')';
DlmanageUtils.sqlProductVideoDvd = '(d.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_VIDEODVD)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\' OR d.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_VIDEODVD_BLURAY)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\')';
DlmanageUtils.sqlAlbumDesign = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_ALBUM_DESIGN)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlMail = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_MAIL)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlMailVideo = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_MAIL_VIDEO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlCustomTask = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_CUSTOM)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlSlideshow = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_SLIDESHOW)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlSlideshowOL = 'd.pi_model = \'<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_SLIDESHOW_OL)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';


DlmanageUtils.sqlCommonEnlargement = 'd.pi_type == \'<?php echo ((is_array($_tmp=@SAMPLE_TYPE_ENLARGEMENT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlCommonNotEnlargement = 'd.pi_type != \'<?php echo ((is_array($_tmp=@SAMPLE_TYPE_ENLARGEMENT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';

DlmanageUtils.sqlNyk = ' AND d.branch = \'<?php echo ((is_array($_tmp=@NEWYORK)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlSyd = ' AND d.branch = \'<?php echo ((is_array($_tmp=@SYDNEY)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlAuk = ' AND d.branch = \'<?php echo ((is_array($_tmp=@AUCKLAND)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlMeb = ' AND d.branch = \'<?php echo ((is_array($_tmp=@MELBOURNE)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlXtr = ' AND d.branch = \'<?php echo ((is_array($_tmp=@XTRAORDINARY)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
DlmanageUtils.sqlBne = ' AND d.branch = \'<?php echo ((is_array($_tmp=@BRISBANE)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';

/* 经理助理端ALLTASKS */
DlmanageUtils.allAsstTasks = '(' + DlmanageUtils.sqlPrecon + ' OR ' + DlmanageUtils.sqlMusic + ' OR ' + DlmanageUtils.sqlRequirement + ' OR ' + DlmanageUtils.sqlPhotographer + ' OR ' + DlmanageUtils.sqlVideographer + ' OR ' + DlmanageUtils.sqlMakeup + ' OR ' + DlmanageUtils.sqlLight + ' OR ' +  DlmanageUtils.sqlProductVideo + ' OR ' +  DlmanageUtils.sqlProductVideoB + ' OR ' + DlmanageUtils.sqlProductVideoDvd + ' OR ' + DlmanageUtils.sqlProduct4x6 + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + ' OR ' + DlmanageUtils.sqlMail + ')';
/* 经理端ALLTASKS */
DlmanageUtils.allManaTasks = '(d.cancelled = 0 AND ' + '(' + DlmanageUtils.sqlPrecon + ' OR ' + DlmanageUtils.sqlMusic + ' OR ' + DlmanageUtils.sqlRequirement + ' OR ' + DlmanageUtils.sqlPhotographer + ' OR ' + DlmanageUtils.sqlVideographer + ' OR ' + DlmanageUtils.sqlMakeup + ' OR ' + DlmanageUtils.sqlLight + ' OR ' +  DlmanageUtils.sqlProductVideo + ' OR ' +  DlmanageUtils.sqlProductVideoB  + ' OR ' + DlmanageUtils.sqlProductVideoDvd + ' OR ' + DlmanageUtils.sqlProduct4x6 + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + ' OR ' + DlmanageUtils.sqlMail + '))';
/* 客服端ALLTASKS */
DlmanageUtils.allServTasks = '(' + DlmanageUtils.sqlMusic + ' OR ' + DlmanageUtils.sqlRequirement + ' OR ' + DlmanageUtils.sqlVideographer + ' OR ' + DlmanageUtils.sqlProductVideo + ' OR ' +  DlmanageUtils.sqlProductVideoB  + ' OR ' + DlmanageUtils.sqlProductVideoDvd + ' OR ' + DlmanageUtils.sqlProduct4x6 + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlMailVideo + ' OR ' + DlmanageUtils.sqlAlbumDesign + ')';
/* 工厂端ALLTASKS */
DlmanageUtils.allFactTasks = '(' + DlmanageUtils.sqlProductVideo + ' OR ' +  DlmanageUtils.sqlProductVideoB  + ' OR ' + DlmanageUtils.sqlProductVideoDvd + ' OR ' + DlmanageUtils.sqlProduct4x6 + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + ' OR ' + DlmanageUtils.sqlMail + ')';
/* 设计师端ALLTASKS */
DlmanageUtils.allDesignerTasks = '(' + DlmanageUtils.sqlProductVideo + ' OR ' +  DlmanageUtils.sqlProductVideoB  + ' OR ' + DlmanageUtils.sqlProductVideoDvd + ' OR ' + DlmanageUtils.sqlProduct4x6 + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + ')';
/* 剪辑师端ALLTASKS */
DlmanageUtils.allEditorTasks = '(' + DlmanageUtils.sqlProductVideo + ' OR ' +  DlmanageUtils.sqlProductVideoB  + ' OR ' + DlmanageUtils.sqlProductVideoDvd + ' OR ' + DlmanageUtils.sqlMailVideo + ' OR ' + DlmanageUtils.sqlVideographer + ')';
/* 会计端ALLTASKS */
DlmanageUtils.allAcctTasks = '(' + DlmanageUtils.sqlPrecon + ' OR ' + DlmanageUtils.sqlMusic + ' OR ' + DlmanageUtils.sqlRequirement + ' OR ' + DlmanageUtils.sqlPhotographer + ' OR ' + DlmanageUtils.sqlVideographer + ' OR ' + DlmanageUtils.sqlMakeup + ' OR ' + DlmanageUtils.sqlLight + ' OR ' +  DlmanageUtils.sqlProductVideo + ' OR ' +  DlmanageUtils.sqlProductVideoB  + ' OR ' + DlmanageUtils.sqlProductVideoDvd + ' OR ' + DlmanageUtils.sqlProduct4x6 + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + ' OR ' + DlmanageUtils.sqlMail + ')';


DlmanageUtils.allProducts = '(' + DlmanageUtils.sqlProductVideo + ' OR ' + DlmanageUtils.sqlProductVideoDvd + ' OR ' + DlmanageUtils.sqlProduct4x6 + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + ')';
DlmanageUtils.allProductsVideo = '(' + DlmanageUtils.sqlProductVideo + ' OR ' +  DlmanageUtils.sqlProductVideoB  + ' OR ' + DlmanageUtils.sqlProductVideoDvd + ')';
DlmanageUtils.allMails = '(' + DlmanageUtils.sqlMail + ')';

DlmanageUtils.ownerWorks = '(d.cancelled = 0 AND d.isCustom = 1 AND (d.state = 2 OR d.state = 4) AND ' + DlmanageUtils.sqlCustomTask + ')';
DlmanageUtils.assigneeWorks = '(d.cancelled = 0 AND d.isCustom = 1 AND (d.state = 1 OR d.state = 3) AND ' + DlmanageUtils.sqlCustomTask + ')';
DlmanageUtils.customWorks = '(d.cancelled = 0 AND d.isCustom = 1 AND (d.state = 2) AND ' + DlmanageUtils.sqlCustomTask + ')';
DlmanageUtils.allCustomWorks = '(d.isCustom = 1 AND (d.state = 1 OR d.state = 2 OR d.state = 3 OR d.state = 4 OR d.state = 5) AND ' + DlmanageUtils.sqlCustomTask + ')';

DlmanageUtils.asstAssignWork = '(d.cancelled = 0 AND d.state = 1 AND (' + DlmanageUtils.sqlPhotographer + ' OR ' + DlmanageUtils.sqlVideographer + ' OR ' + DlmanageUtils.sqlMakeup + ' OR ' + DlmanageUtils.sqlLight + '))';
DlmanageUtils.asstConfirmAssignee = '(d.cancelled = 0 AND d.state = 2 AND (' + DlmanageUtils.sqlPhotographer + ' OR ' + DlmanageUtils.sqlVideographer + ' OR ' + DlmanageUtils.sqlMakeup + ' OR ' + DlmanageUtils.sqlLight + '))';
DlmanageUtils.asstRemindAssignee = '(d.cancelled = 0 AND d.state = 3 AND (' + DlmanageUtils.sqlPhotographer + ' OR ' + DlmanageUtils.sqlVideographer + ' OR ' + DlmanageUtils.sqlMakeup + ' OR ' + DlmanageUtils.sqlLight + '))';
DlmanageUtils.asstPrecon = '(d.cancelled = 0 AND d.state = 1 AND (' + DlmanageUtils.sqlPrecon + '))';
DlmanageUtils.asstMusic = '(d.cancelled = 0 AND (d.state = 1) AND (' + DlmanageUtils.sqlMusic + '))';
DlmanageUtils.asstRequirement = '(d.cancelled = 0 AND (d.state = 1) AND (' + DlmanageUtils.sqlRequirement + '))';
DlmanageUtils.asstCollectDvd = '(d.cancelled = 0 AND d.state = 4 AND (' + DlmanageUtils.sqlPhotographer + ' OR ' + DlmanageUtils.sqlVideographer + '))';
DlmanageUtils.asstBackupDvd = '(d.cancelled = 0 AND d.state = 5 AND (' + DlmanageUtils.sqlPhotographer + ' OR ' + DlmanageUtils.sqlVideographer + '))';
DlmanageUtils.asstTakeDvd = '(d.cancelled = 0 AND d.state = 6 AND (' + DlmanageUtils.sqlPhotographer + '))';
DlmanageUtils.asstReturnForm = '(d.cancelled = 0 AND d.state = 1 AND (' + DlmanageUtils.sqlProduct4x6 + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + ' OR ' + DlmanageUtils.sqlSlideshow + ' OR ' + DlmanageUtils.sqlSlideshowOL + '))';
DlmanageUtils.asstReceiveFeedback = '(d.cancelled = 0 AND d.state = 7 AND (' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + ' OR ' + DlmanageUtils.sqlSlideshow + ' OR ' + DlmanageUtils.sqlSlideshowOL + '))';
DlmanageUtils.asstReceiveFeedbackVideo = '(d.cancelled = 0 AND ( ( d.state = 7 AND ' + DlmanageUtils.sqlProductVideo + ') OR  ( d.state = 7 AND ' + DlmanageUtils.sqlProductVideoB + ') ) )';
DlmanageUtils.asstTakeProduct = '(d.cancelled = 0 AND ((d.state = 11 AND ' + DlmanageUtils.sqlProduct4x6 + ') OR (d.state = 13 AND ' + DlmanageUtils.sqlProductRetouch + ') OR (d.state = 17 AND ' + DlmanageUtils.sqlProductCommon + ') OR (d.state = 6 AND ' + DlmanageUtils.sqlProductVideoDvd + ') OR (d.state = 10 AND ' + DlmanageUtils.sqlSlideshow + ') OR (d.state = 10 AND ' + DlmanageUtils.sqlSlideshowOL + ') OR (d.state = 17 AND ' + DlmanageUtils.sqlProductRetouchMagazine + ')))';
DlmanageUtils.asstReceiveProduct = '(d.cancelled = 0 AND d.state = 1 AND (' + DlmanageUtils.sqlMail + '))';
DlmanageUtils.asstTasks = DlmanageUtils.asstAssignWork + ' OR ' + DlmanageUtils.asstConfirmAssignee + ' OR ' + DlmanageUtils.asstRemindAssignee + ' OR ' + DlmanageUtils.asstPrecon + ' OR ' + DlmanageUtils.asstMusic + ' OR ' + DlmanageUtils.asstRequirement + ' OR ' + DlmanageUtils.asstCollectDvd + ' OR ' + DlmanageUtils.asstBackupDvd + ' OR ' + DlmanageUtils.asstTakeDvd + ' OR ' + DlmanageUtils.asstReturnForm + ' OR ' + DlmanageUtils.asstReceiveFeedback + ' OR ' + DlmanageUtils.asstReceiveFeedbackVideo + ' OR ' + DlmanageUtils.asstTakeProduct + ' OR ' + DlmanageUtils.asstReturnForm + ' OR ' + DlmanageUtils.asstReceiveFeedback + ' OR ' + DlmanageUtils.asstReceiveFeedbackVideo + ' OR ' + DlmanageUtils.asstTakeProduct + ' OR ' + DlmanageUtils.asstReceiveProduct;  


DlmanageUtils.servChooseDesigner = '(d.cancelled = 0 AND d.state = 2 AND (' + DlmanageUtils.sqlProduct4x6 + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + ' OR ' + DlmanageUtils.sqlSlideshow + ' OR ' + DlmanageUtils.sqlSlideshowOL + '))';
DlmanageUtils.servTranslateUploadForm = '(d.cancelled = 0 AND d.state = 3 AND (' + DlmanageUtils.sqlProduct4x6 + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + ' OR ' + DlmanageUtils.sqlSlideshow + ' OR ' + DlmanageUtils.sqlSlideshowOL + '))';
DlmanageUtils.servWrap4x6Photo = '(d.cancelled = 0 AND d.state = 5 AND (' + DlmanageUtils.sqlProduct4x6 + '))';
DlmanageUtils.servBurnRetouchDvd = '(d.cancelled = 0 AND d.state = 12 AND (' + DlmanageUtils.sqlProductRetouch + '))';
DlmanageUtils.servCheckSendDesign = '(d.cancelled = 0 AND d.state = 6 AND (' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + '))';
DlmanageUtils.servConfirmWork = '(d.cancelled = 0 AND (d.state = 7 OR d.state = 8) AND (' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + '))';
DlmanageUtils.servTranslateUploadChange = '(d.cancelled = 0 AND d.state = 9 AND (' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + '))';
DlmanageUtils.servSendLink = '(d.cancelled = 0 AND (  ( d.state = 6 AND ' + DlmanageUtils.sqlProductVideo + ') OR  ( d.state = 6 AND ' + DlmanageUtils.sqlProductVideoB + ') ) )';
DlmanageUtils.servConfirmPreview = '(d.cancelled = 0 AND (  ( (d.state = 7 OR d.state = 8) AND (' + DlmanageUtils.sqlProductVideo + ') ) OR ( (d.state = 7 OR d.state = 8) AND (' + DlmanageUtils.sqlProductVideoB + ') ) ) )';
DlmanageUtils.servModifyPreview = '(d.cancelled = 0 AND (  ( d.state = 9 AND (' + DlmanageUtils.sqlProductVideo + ') ) OR ( d.state = 9 AND (' + DlmanageUtils.sqlProductVideoB + ') )  ) )';
DlmanageUtils.servUploadCover = '(d.cancelled = 0 AND  ( (d.state = 11 AND (' + DlmanageUtils.sqlProductVideo + ')) OR (d.state = 11 AND (' + DlmanageUtils.sqlProductVideoB + '))  ) )';
DlmanageUtils.servFixProblem = '(d.cancelled = 0 AND ((d.state = 13 AND ' + DlmanageUtils.sqlProduct4x6 + ') OR (d.state = 15 AND ' + DlmanageUtils.sqlProductRetouch + ') OR (d.state = 19 AND ' + DlmanageUtils.sqlProductCommon + ')))';
DlmanageUtils.servModifyFinal = '(d.cancelled = 0 AND d.state = 8 AND (' + DlmanageUtils.sqlProductVideoDvd + '))';
DlmanageUtils.servBackupTape = '(d.cancelled = 0 AND d.state = 5 AND (' + DlmanageUtils.sqlVideographer + ' OR ' + DlmanageUtils.sqlPhotographer + '))';
DlmanageUtils.servSendTape = '(d.cancelled = 0 AND d.state = 2 AND (' + DlmanageUtils.sqlProductVideo + ' OR ' + DlmanageUtils.sqlProductVideoB + '))';
DlmanageUtils.servMusic = '(d.cancelled = 0 AND (d.state = 1 OR d.state = 2) AND (' + DlmanageUtils.sqlMusic + '))';
DlmanageUtils.servRequirement = '(d.cancelled = 0 AND (d.state = 1 OR d.state = 2) AND (' + DlmanageUtils.sqlRequirement + '))';
DlmanageUtils.servTasks = DlmanageUtils.servChooseDesigner + ' OR ' + DlmanageUtils.servTranslateUploadForm + ' OR ' + DlmanageUtils.servWrap4x6Photo + ' OR ' + DlmanageUtils.servBurnRetouchDvd + ' OR ' + DlmanageUtils.servCheckSendDesign + ' OR ' + DlmanageUtils.servConfirmWork + ' OR ' + DlmanageUtils.servTranslateUploadChange + ' OR ' + DlmanageUtils.servSendLink + ' OR ' + DlmanageUtils.servConfirmPreview + ' OR ' + DlmanageUtils.servModifyPreview + ' OR ' + DlmanageUtils.servUploadCover + ' OR ' + DlmanageUtils.servFixProblem + ' OR ' + DlmanageUtils.servModifyFinal + ' OR ' + DlmanageUtils.servBackupTape + ' OR ' + DlmanageUtils.servSendTape + ' OR ' + DlmanageUtils.servMusic + ' OR ' + DlmanageUtils.servRequirement; 

DlmanageUtils.designerCompleteDesign = '(d.cancelled = 0 AND (d.state = 4 OR d.state = 5) AND (' + DlmanageUtils.sqlAlbumDesign + ') AND (d.modified = false))';
DlmanageUtils.designerModifyDesign = '(d.cancelled = 0 AND ((d.state = 5 OR d.state = 10) AND (' + DlmanageUtils.sqlAlbumDesign + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ')' + ' AND (d.modified = true))' + ')';
DlmanageUtils.designerDownloadChange = '(d.cancelled = 0 AND (((d.state = 5) AND (' + DlmanageUtils.sqlSlideshow + ' OR ' + DlmanageUtils.sqlSlideshowOL + '))' + ' OR ' + '((d.state = 4 OR d.state = 5) AND (' + DlmanageUtils.sqlProduct4x6 + '))' + ' OR ' + '((d.state = 4 OR d.state = 5) AND (' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ')' + ' AND d.modified = false))' + ')';
DlmanageUtils.designerPhoto4x6 = '(d.cancelled = 0 AND d.state = 8 AND (' + DlmanageUtils.sqlProduct4x6 + '))';
DlmanageUtils.designerUploadDesign = '(d.cancelled = 0 AND d.state = 11 AND (' + DlmanageUtils.sqlProductRetouch + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ' OR ' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlAlbumDesign + '))';
DlmanageUtils.designerTasks = '(' + DlmanageUtils.designerCompleteDesign + ' OR ' + DlmanageUtils.designerModifyDesign + ' OR ' + DlmanageUtils.designerDownloadChange + ' OR ' + DlmanageUtils.designerPhoto4x6 + ' OR ' + DlmanageUtils.designerUploadDesign + ')';


DlmanageUtils.factoryDownloadPrint = '(d.cancelled = 0 AND ((d.state = 12 OR d.state = 13) AND (' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ')) OR (d.state = 12 AND ' + DlmanageUtils.sqlAlbumDesign + '))';
DlmanageUtils.factoryManufacture = '(d.cancelled = 0 AND d.state = 14 AND (' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + '))';
DlmanageUtils.factoryReceive = '(d.cancelled = 0 AND (d.state = 8 AND (' + DlmanageUtils.sqlProduct4x6 + ')) OR (d.state = 3 AND (' + DlmanageUtils.sqlProductVideoDvd + '))OR (d.state = 6 AND (' + DlmanageUtils.sqlSlideshow + '))OR (d.state = 6 AND (' + DlmanageUtils.sqlSlideshowOL + ')))';
DlmanageUtils.factoryTasks = DlmanageUtils.factoryReceive + ' OR ' + DlmanageUtils.factoryDownloadPrint + ' OR ' + DlmanageUtils.factoryManufacture;
DlmanageUtils.factorySend = '(d.cancelled = 0 AND (d.state = 15 AND (' + DlmanageUtils.sqlProductCommon + ' OR ' + DlmanageUtils.sqlProductRetouchMagazine + ')) OR (d.state = 9 AND ' + DlmanageUtils.sqlProduct4x6 + ') OR (d.state = 4 AND ' + DlmanageUtils.sqlProductVideoDvd + ') OR (d.state = 7 AND ' + DlmanageUtils.sqlSlideshow + ') OR (d.state = 7 AND ' + DlmanageUtils.sqlSlideshowOL + '))';


DlmanageUtils.editorCaijiVideoTape = '(d.cancelled = 0 AND d.state = 4 AND ( (' + DlmanageUtils.sqlProductVideo + ')  OR  ('+DlmanageUtils.sqlProductVideoB + ') ))';
DlmanageUtils.editorReceiveTape = '(d.cancelled = 0 AND d.state = 1 AND (' + DlmanageUtils.sqlMailVideo + '))';
DlmanageUtils.editorCompletePreview = '(d.cancelled = 0 AND ( ( (d.state = 5) AND (' + DlmanageUtils.sqlProductVideo + ') ) OR ( (d.state = 5) AND (' + DlmanageUtils.sqlProductVideoB + ') ) ) AND (d.modified = false))';
DlmanageUtils.editorModifyPreview = '(d.cancelled = 0 AND ( ( (d.state = 5 OR d.state = 10) AND (' + DlmanageUtils.sqlProductVideo + ') ) OR ( (d.state = 5 OR d.state = 10) AND (' + DlmanageUtils.sqlProductVideoB + ') ) )  AND (d.modified = true))';
DlmanageUtils.editorCompleteFinal = '(d.cancelled = 0 AND (d.state = 1) AND (' + DlmanageUtils.sqlProductVideoDvd + ') AND (d.modified = false))';
DlmanageUtils.editorModifyFinal = '(d.cancelled = 0 AND (d.state = 1 OR d.state = 9) AND (' + DlmanageUtils.sqlProductVideoDvd + ') AND (d.modified = true))';
DlmanageUtils.editorSend = '(d.cancelled = 0 AND (d.state = 2) AND (' + DlmanageUtils.sqlProductVideoDvd + '))';
DlmanageUtils.editorTasks = DlmanageUtils.editorCaijiVideoTape + ' OR ' + DlmanageUtils.editorReceiveTape + ' OR ' + DlmanageUtils.editorCompletePreview + ' OR ' + DlmanageUtils.editorModifyPreview + ' OR ' + DlmanageUtils.editorCompleteFinal + ' OR ' + DlmanageUtils.editorModifyFinal + ' OR ' + DlmanageUtils.editorSend;

DlmanageUtils.servAllocateEditor = '(d.cancelled = 0 AND (  ( d.state = 1 AND ' + DlmanageUtils.sqlProductVideo + ')  ) )';

DlmanageUtils.sydSend = DlmanageUtils.factorySend + DlmanageUtils.sqlSyd;
DlmanageUtils.aukSend = DlmanageUtils.factorySend + DlmanageUtils.sqlAuk;
DlmanageUtils.mebSend = DlmanageUtils.factorySend + DlmanageUtils.sqlMeb;
DlmanageUtils.nykSend = DlmanageUtils.factorySend + DlmanageUtils.sqlNyk;
DlmanageUtils.xtSend = DlmanageUtils.factorySend + DlmanageUtils.sqlXtr;
DlmanageUtils.bneSend = DlmanageUtils.factorySend + DlmanageUtils.sqlBne;

DlmanageUtils.tableCustomer = 'ns_v1customer';
DlmanageUtils.tableMyOrder = 'ns_v1myorder';
//DlmanageUtils.tableMyOrderCancel = 'ns_MyOrderCancel';
//DlmanageUtils.tableCustomerContact = 'ns_CustomerContact';

/**
 *经理助理端smryArgs
*/
DlmanageUtils.asstSmryArgs = function(smryGui, operator) {
  if (smryGui.jobs) {
    var smryArgs = [ { name: smryGui.jobs.id, cond: DlmanageUtils.asstTasks + ' OR ' + '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' },
                     { name: smryGui.asstTasks.id, cond: DlmanageUtils.asstTasks + ' OR ' + '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' },
                     { name: smryGui.assingWorker.id, cond: DlmanageUtils.asstAssignWork },
                     { name: smryGui.confirmAssignee.id, cond: DlmanageUtils.asstConfirmAssignee },
                     { name: smryGui.remindAssignee.id, cond: DlmanageUtils.asstRemindAssignee },
                     { name: smryGui.precon.id, cond: DlmanageUtils.asstPrecon },
                     { name: smryGui.music.id, cond: DlmanageUtils.asstMusic },
                     { name: smryGui.requirement.id, cond: DlmanageUtils.asstRequirement },
                     { name: smryGui.collectDvd.id, cond: DlmanageUtils.asstCollectDvd },
                     { name: smryGui.backDvd.id, cond: DlmanageUtils.asstBackupDvd },
                     { name: smryGui.takeDvd.id, cond: DlmanageUtils.asstTakeDvd },
                     { name: smryGui.returnForm.id, cond: DlmanageUtils.asstReturnForm },
                     { name: smryGui.feedback.id, cond: DlmanageUtils.asstReceiveFeedback },
                     { name: smryGui.feedbackVideo.id, cond: DlmanageUtils.asstReceiveFeedbackVideo},
                     { name: smryGui.takeProducts.id, cond: DlmanageUtils.asstTakeProduct },
                     { name: smryGui.receives.id, cond: DlmanageUtils.asstReceiveProduct },
                     { name: smryGui.ownerworks.id, cond: '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' }
                   ];
  } else {
    var smryArgs = [ { name: smryGui.asstTasks.id, cond: DlmanageUtils.asstTasks },
                     { name: smryGui.assingWorker.id, cond: DlmanageUtils.asstAssignWork },
                     { name: smryGui.confirmAssignee.id, cond: DlmanageUtils.asstConfirmAssignee },
                     { name: smryGui.remindAssignee.id, cond: DlmanageUtils.asstRemindAssignee },
                     { name: smryGui.precon.id, cond: DlmanageUtils.asstPrecon },
                     { name: smryGui.music.id, cond: DlmanageUtils.asstMusic },
                     { name: smryGui.requirement.id, cond: DlmanageUtils.asstRequirement },
                     { name: smryGui.collectDvd.id, cond: DlmanageUtils.asstCollectDvd },
                     { name: smryGui.backDvd.id, cond: DlmanageUtils.asstBackupDvd },
                     { name: smryGui.takeDvd.id, cond: DlmanageUtils.asstTakeDvd },
                     { name: smryGui.returnForm.id, cond: DlmanageUtils.asstReturnForm },
                     { name: smryGui.feedback.id, cond: DlmanageUtils.asstReceiveFeedback },
                     { name: smryGui.feedbackVideo.id, cond: DlmanageUtils.asstReceiveFeedbackVideo},
                     { name: smryGui.takeProducts.id, cond: DlmanageUtils.asstTakeProduct },
                     { name: smryGui.receives.id, cond: DlmanageUtils.asstReceiveProduct },
                   ];
  }
  return smryArgs;
}

/**
 *客服端smryArgs
 */
DlmanageUtils.servSmryArgs = function(smryGui, operator) {
  if (smryGui.jobs) {
    var smryArgs = [ { name: smryGui.jobs.id, cond: DlmanageUtils.servTasks + ' OR ' + '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))'},
                     { name: smryGui.servTasks.id, cond: DlmanageUtils.servTasks + ' OR ' + '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))'},
                     { name: smryGui.chooseDesigner.id, cond: DlmanageUtils.servChooseDesigner },
                     { name: smryGui.uploadForm.id, cond: DlmanageUtils.servTranslateUploadForm },
                     { name: smryGui.compress4x6.id, cond: DlmanageUtils.servWrap4x6Photo },
                     { name: smryGui.burnRetouch.id, cond: DlmanageUtils.servBurnRetouchDvd },
                     { name: smryGui.sendDesign.id, cond: DlmanageUtils.servCheckSendDesign },
                     { name: smryGui.confirmDesign.id, cond: DlmanageUtils.servConfirmWork },
                     { name: smryGui.translateChanges.id, cond: DlmanageUtils.servTranslateUploadChange },
					 { name: smryGui.allocateEditor.id, cond: DlmanageUtils.servAllocateEditor },
                     { name: smryGui.sendLink.id, cond: DlmanageUtils.servSendLink },
                     { name: smryGui.confirmPreview.id, cond: DlmanageUtils.servConfirmPreview },
                     { name: smryGui.backupTape.id, cond: DlmanageUtils.servBackupTape },
                     { name: smryGui.sendTape.id, cond: DlmanageUtils.servSendTape },
                     { name: smryGui.uploadMusic.id, cond: DlmanageUtils.servMusic },
                     { name: smryGui.uploadRequirement.id, cond: DlmanageUtils.servRequirement },
                     { name: smryGui.modifyPreview.id, cond: DlmanageUtils.servModifyPreview },
                     { name: smryGui.uploadCover.id, cond: DlmanageUtils.servUploadCover },
                     { name: smryGui.fixProduct.id, cond: DlmanageUtils.servFixProblem },
                     { name: smryGui.modifyFinal.id, cond: DlmanageUtils.servModifyFinal },
                     { name: smryGui.ownerworks.id, cond: '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' }
                   ];
  } else {
    var smryArgs = [ { name: smryGui.servTasks.id, cond: DlmanageUtils.servTasks },
                     { name: smryGui.chooseDesigner.id, cond: DlmanageUtils.servChooseDesigner },
                     { name: smryGui.uploadForm.id, cond: DlmanageUtils.servTranslateUploadForm },
                     { name: smryGui.compress4x6.id, cond: DlmanageUtils.servWrap4x6Photo },
                     { name: smryGui.burnRetouch.id, cond: DlmanageUtils.servBurnRetouchDvd },
                     { name: smryGui.sendDesign.id, cond: DlmanageUtils.servCheckSendDesign },
                     { name: smryGui.confirmDesign.id, cond: DlmanageUtils.servConfirmWork },
                     { name: smryGui.translateChanges.id, cond: DlmanageUtils.servTranslateUploadChange },
					 { name: smryGui.allocateEditor.id, cond: DlmanageUtils.servAllocateEditor },
                     { name: smryGui.sendLink.id, cond: DlmanageUtils.servSendLink },
                     { name: smryGui.confirmPreview.id, cond: DlmanageUtils.servConfirmPreview },
                     { name: smryGui.backupTape.id, cond: DlmanageUtils.servBackupTape },
                     { name: smryGui.sendTape.id, cond: DlmanageUtils.servSendTape },
                     { name: smryGui.uploadMusic.id, cond: DlmanageUtils.servMusic },
                     { name: smryGui.uploadRequirement.id, cond: DlmanageUtils.servRequirement },
                     { name: smryGui.modifyPreview.id, cond: DlmanageUtils.servModifyPreview },
                     { name: smryGui.uploadCover.id, cond: DlmanageUtils.servUploadCover },
                     { name: smryGui.fixProduct.id, cond: DlmanageUtils.servFixProblem },
                     { name: smryGui.modifyFinal.id, cond: DlmanageUtils.servModifyFinal }
                   ];
  }
  return smryArgs;
}

/**
 *经理端smryArgs
 */
DlmanageUtils.managerSmryArgs = function(smryGui, operator) {
  var smryArgs = [ { name: smryGui.jobs.id, cond: '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' },
                   { name: smryGui.ownerworks.id, cond: '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' }
                 ];
  return smryArgs;
}

/**
 *会计端smryArgs
 */
DlmanageUtils.acctSmryArgs = function(smryGui, operator) {
  var smryArgs = [ { name: smryGui.jobs.id, cond: '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' },
                   { name: smryGui.ownerworks.id, cond: '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' }
                 ];
  return smryArgs;
}

/**
 *工厂端smryArgs
 */
DlmanageUtils.factSmryArgs = function(smryGui, operator) {
  if (smryGui.jobs && smryGui.sends) {
    var smryArgs = [ { name: smryGui.jobs.id, cond: DlmanageUtils.factoryTasks + ' OR ' + '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))'},
                     { name: smryGui.sends.id, cond: DlmanageUtils.factorySend },
                     { name: smryGui.factoryTasks.id, cond: DlmanageUtils.factoryTasks + ' OR ' + '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))'},
                     { name: smryGui.receive4x6.id, cond: DlmanageUtils.factoryReceive },
                     { name: smryGui.downloadAndPrint.id, cond: DlmanageUtils.factoryDownloadPrint },
                     { name: smryGui.complete.id, cond: DlmanageUtils.factoryManufacture },
                     { name: smryGui.ownerworks.id, cond: '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' }
                   ];
  } else {
    var smryArgs = [ { name: smryGui.factoryTasks.id, cond: DlmanageUtils.factoryTasks },
                     { name: smryGui.receive4x6.id, cond: DlmanageUtils.factoryReceive },
                     { name: smryGui.downloadAndPrint.id, cond: DlmanageUtils.factoryDownloadPrint },
                     { name: smryGui.complete.id, cond: DlmanageUtils.factoryManufacture }
                   ];
  }
  return smryArgs;
}

/**
 *设计师端smryArgs
 */
DlmanageUtils.desSmryArgs = function(smryGui, operator) {
  if (smryGui.jobs) {
    var smryArgs = [ { name: smryGui.jobs.id, cond: DlmanageUtils.designerTasks + ' AND d.user_trackId = \'' + operator.trackId + '\'' + ' OR ' + '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))'},
                     { name: smryGui.designerTasks.id, cond: DlmanageUtils.designerTasks + ' AND d.user_trackId = \'' + operator.trackId + '\'' + ' OR ' + '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' },
                     { name: smryGui.design.id, cond: DlmanageUtils.designerCompleteDesign + ' AND d.user_trackId = \'' + operator.trackId + '\'' },
                     { name: smryGui.designChange.id, cond: DlmanageUtils.designerModifyDesign + ' AND d.user_trackId = \'' + operator.trackId + '\'' },
                     { name: smryGui.photo.id, cond: DlmanageUtils.designerDownloadChange + ' AND d.user_trackId = \'' + operator.trackId + '\'' },
                     { name: smryGui.send4x6.id, cond: DlmanageUtils.designerPhoto4x6 + ' AND d.user_trackId = \'' + operator.trackId + '\'' },
                     { name: smryGui.uploadDesign.id, cond: DlmanageUtils.designerUploadDesign + ' AND d.user_trackId = \'' + operator.trackId + '\'' },
                     { name: smryGui.ownerworks.id, cond: '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' }
                   ];
  } else {
    var smryArgs = [ { name: smryGui.designerTasks.id, cond: DlmanageUtils.designerTasks + ' AND d.user_trackId = \'' + operator.trackId + '\'' },
                     { name: smryGui.design.id, cond: DlmanageUtils.designerCompleteDesign + ' AND d.user_trackId = \'' + operator.trackId + '\'' },
                     { name: smryGui.designChange.id, cond: DlmanageUtils.designerModifyDesign + ' AND d.user_trackId = \'' + operator.trackId + '\'' },
                     { name: smryGui.photo.id, cond: DlmanageUtils.designerDownloadChange + ' AND d.user_trackId = \'' + operator.trackId + '\'' },
                     { name: smryGui.send4x6.id, cond: DlmanageUtils.designerPhoto4x6 + ' AND d.user_trackId = \'' + operator.trackId + '\'' },
                     { name: smryGui.uploadDesign.id, cond: DlmanageUtils.designerUploadDesign + ' AND d.user_trackId = \'' + operator.trackId + '\'' }
                   ];
  }
  return smryArgs;
}

/**
 *剪辑师端smryArgs
 */
DlmanageUtils.editSmryArgs = function(smryGui, operator) {
  if (smryGui.jobs) {
	    var smryArgs = [ { name: smryGui.jobs.id, cond: '(' + DlmanageUtils.editorTasks + ' OR ' + '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\')) )' + ' AND (d.user_trackId = \'' + operator.trackId + '\')' },
	                     { name: smryGui.editorTasks.id, cond: '('+ DlmanageUtils.editorTasks + ' OR ' + '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\')) )'+' AND (d.user_trackId = \'' + operator.trackId + '\')' },
	                     { name: smryGui.receiveTape.id, cond: '(' + DlmanageUtils.editorReceiveTape +') AND (d.user_trackId = \'' + operator.trackId + '\')' },
	                     { name: smryGui.completePreview.id, cond:  '(' + DlmanageUtils.editorCompletePreview+') AND (d.user_trackId = \'' + operator.trackId + '\')' },
	                     { name: smryGui.modifyPreview.id, cond:  '(' + DlmanageUtils.editorModifyPreview+') AND (d.user_trackId = \'' + operator.trackId + '\')' },
	                     { name: smryGui.completeFinal.id, cond: '(' +  DlmanageUtils.editorCompleteFinal+') AND (d.user_trackId = \'' + operator.trackId + '\')' },
	                     { name: smryGui.modifyFinal.id, cond: '(' +  DlmanageUtils.editorModifyFinal+') AND (d.user_trackId = \'' + operator.trackId + '\')' },
	                     { name: smryGui.caijiVideoTape.id, cond: '(' +  DlmanageUtils.editorCaijiVideoTape+') AND (d.user_trackId = \'' + operator.trackId + '\')' },
	                     { name: smryGui.send.id, cond: '(' +  DlmanageUtils.editorSend+') AND (d.user_trackId = \'' + operator.trackId + '\')' },
	                     { name: smryGui.ownerworks.id, cond: '(' + DlmanageUtils.ownerWorks + ' AND (d.ownerTrackId = \'' + operator.trackId + '\'))' + ' OR (' + DlmanageUtils.assigneeWorks + ' AND (d.user_trackId = \'' + operator.trackId + '\'))' }
	                   ];
  } else {
		    var smryArgs = [ { name: smryGui.editorTasks.id, cond:  '(' + DlmanageUtils.editorTasks+') AND (d.user_trackId = \'' + operator.trackId + '\')' },
		                     { name: smryGui.receiveTape.id, cond:  '(' + DlmanageUtils.editorReceiveTape+') AND (d.user_trackId = \'' + operator.trackId + '\')' },
		                     { name: smryGui.completePreview.id, cond:  '(' + DlmanageUtils.editorCompletePreview +') AND (d.user_trackId = \'' + operator.trackId + '\')'},
		                     { name: smryGui.modifyPreview.id, cond:  '(' + DlmanageUtils.editorModifyPreview +') AND (d.user_trackId = \'' + operator.trackId + '\')'},
		                     { name: smryGui.completeFinal.id, cond:  '(' + DlmanageUtils.editorCompleteFinal +') AND (d.user_trackId = \'' + operator.trackId + '\')'},
		                     { name: smryGui.modifyFinal.id, cond:  '(' + DlmanageUtils.editorModifyFinal +') AND (d.user_trackId = \'' + operator.trackId + '\')'},
		                     { name: smryGui.caijiVideoTape.id, cond:  '(' + DlmanageUtils.editorCaijiVideoTape +') AND (d.user_trackId = \'' + operator.trackId + '\')'},
		                     { name: smryGui.send.id, cond:  '(' + DlmanageUtils.editorSend +') AND (d.user_trackId = \'' + operator.trackId + '\')'}
		                   ];
  }
  return smryArgs;
}

/**
 * 
 */
DlmanageUtils.text = function(models, modelName, sourceId, targetId, extra) {
  var tmp, model = models[modelName];
  for (var i = 0, il = model.transitions.length; i < il; i++) {
    tmp = model.transitions[i];
    if (tmp.source.id == sourceId && tmp.target.id == targetId) {
      return tmp.source.title + ' (' + tmp.title + ') ' + extra;
    }
  }
  return extra;
};

/**
 * 删除一个对象的所有id,重置它的所有trackId
 */
DlmanageUtils.reproduce = function(arg) {
  var obj = MiscUtils.clone(arg);
  for (var key in obj) {
    if (typeof(obj[key]) == 'object' || typeof(obj[key]) == 'array') {
      obj[key] = this.renew(obj[key]);
    }
    if (key == 'id' || key == 'e_oid') {
      delete obj[key];
    } else if (key == 'trackId') {
      obj[key] = MiscUtils.unique();
    }
  }
  return obj;
};

/**
 * 删除一个对象的所有id
 */
DlmanageUtils.renew = function(arg) {
  var obj = MiscUtils.clone(arg);
  for (var key in obj) {
    if (typeof(obj[key]) == 'object' || typeof(obj[key]) == 'array') {
      obj[key] = this.renew(obj[key]);
    }
    if (key == 'id' || key == 'e_oid') {
      delete obj[key];
    }
  }
  return obj;
};

/**
 * （某些产品的）默认属性和选项
 */
DlmanageUtils.attributes = function(sample) { 
  if (sample == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_ALBUM)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
    return [ { name: '形状', options: [ { name: '横' }, { name: '竖' }, { name: '方' } ] },
             { name: '膜', options: [ { name: '裱膜' }, { name: '淋膜' } ] },
             { name: '封面', options: [ { name: '银沙' }, { name: '铭牌' } ] },
             { name: 'Pages', options: [ { name: '10' }, { name: '11' }, { name: '12' }, { name: '13' }, { name: '14' }, { name: '15' }, { name: '16' }, { name: '17' }, { name: '18' }, { name: '19' }, { name: '20' } ] }
           ];
  } else if (sample == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_MAGAZINE)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
    return [ { name: '形状', options: [ { name: '横' }, { name: '竖' }, { name: '方' } ] },
             { name: '膜', options: [ { name: '亮膜' }, { name: '亚膜' } ] },
             { name: 'Pages', options: [ { name: '10' }, { name: '11' }, { name: '12' }, { name: '13' }, { name: '14' }, { name: '15' }, { name: '16' }, { name: '17' }, { name: '18' }, { name: '19' }, { name: '20' } ] }
           ];
  } else if (sample == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_PHOTOGRAPHER_WITH_HOURS)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
    return [ { name: 'Fav', options: [ { name: '0' }, { name: '5' }, { name: '10' }, { name: '15' }, { name: '20' }, { name: '25' }, { name: '30' }] }];
  }
  return [];
};

/**
 * 根据商品,返回样品
 */
DlmanageUtils.sample = function(product, samples) {
  for (var i = 0, il = samples.length; i < il; i++) {
    sample = samples[i];
    if (sample.id == product.sampleId) {
      return sample;
    }
  }
  return null;
};

DlmanageUtils.sampleAttribute = function(item, sample) {
  for (var j = 0, jl = item.selects.length; j < jl; j++) {
    var sel = item.selects[j];
    for (var i = 0, il = sample.attributes.length; i < il; i++) {
      var attribute = sample.attributes[i];
      var cout = 0;
      if (sel.title != attribute.name) {
        continue;
      }
      for (var k = 0, kl = attribute.options.length; k < kl; k++) {
        var option = attribute.options[k];
        if (sel.value != option.name) {
          cout++;
        } else {
          cout = 0;
        }
      }
      if (cout == attribute.options.length) {
        var opt = v1sampleattributeoption.instance();
        opt.name = sel.value;
        attribute.options[attribute.options.length] = opt;
        continue;
      }
    }
  }
  
  for (var j = 0, jl = item.selects.length; j < jl; j++) {
    var sel = item.selects[j];
    var exist = false;
    for (var i = 0, il = sample.attributes.length; i < il; i++) {
      var attribute = sample.attributes[i];
      if (sel.title == attribute.name) {
        exist = true;
        break;
      }
    }
    if (!exist) {
      var attr = v1sampleattribute.instance();
      attr.name = sel.title;
      var opts = v1sampleattributeoption.instance();
      opts.name = sel.value;
      attr.options[attr.options.length] = opts;
      sample.attributes[sample.attributes.length] = attr;
      continue;
    }
  }
  return sample;
};

/**
 * 根据样品,创建商品
 */
DlmanageUtils.product = function(sample) {
  var product = Product.instance();
  product.sampleId = sample.id;
  product.name = sample.name;
  product.price = sample.price;
  product.type = sample.type;
  product.unit = sample.unit;
  product.model = sample.model;
  product.otherId = MiscUtils.unique();
  product.selects = [];
  for (var i = 0, il = sample.attributes.length; i < il; i++) {
    var attribute = sample.attributes[i];
    this.choose(product, attribute, attribute.options[0]);
  }
  return product;
};

/**
 * 根据样品名称找到SampleId
 */
DlmanageUtils.sampleId = function(samples, package) {
  for (var i = 0, il = samples.length; i < il; i++) {
    sample = samples[i];
    if (sample.type == package.makeup) {
      return sample.id;
    }
    if (package.type == '<?php echo ((is_array($_tmp=@PACKAGE_TYPE_PHOTO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' && sample.name == 'Single Photographer With Hours' && sample.type == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_PHOTOGRAPHER_WITH_HOURS)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      return sample.id;
    }
    if (package.type == '<?php echo ((is_array($_tmp=@PACKAGE_TYPE_VIDEO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' && sample.name == 'Single Videographer With Hours' && sample.type == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_VIDEOGRAPHER_WITH_HOURS)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      return sample.id;
    }
  }
  return '0';
};

/**
 * 记录原始界面对象
 */
DlmanageUtils.initialise = function(elem) {
  if (elem.childNodes.length != 0) {
    elem._protected = true;
  }
  for (var i = 0, il = elem.childNodes.length; i < il; i++) {
    var node = elem.childNodes[i];
    this.initialise(node);
  }
};

/**
 * 清理界面对象
 */
DlmanageUtils.clear = function(gui) {
  for (key in gui) {
    var elem = gui[key];
    if (!elem) {
      continue;
    }
    if (elem.constructor.toString().indexOf('Array') == -1 && elem.constructor.toString().indexOf('Object') == -1) {
      if (!elem._protected) {
        DOMUtils.removeChildElements(elem);
      }
    } else {
      this.clear(elem);
    }
  }
};

/**
 * 检查某商品的某属性中是否选择了某选项
 */
DlmanageUtils.chosen = function(product, attribute, option) {
  for (var i = 0, il = product.selects.length; i < il; i++) {
    var select = product.selects[i];
    if (select.title == attribute.name && select.value == option.name) {
      return true;
    }
  }
  return false;
};

/**
 * 在某商品的某属性中选择了某选项
 */
DlmanageUtils.packageChoose = function(item, attribute, option) {
  for (var i = 0, il = item.selects.length; i < il; i++) {
    var select = item.selects[i];
    if (select.title == attribute.name) {
      item.selects.splice(i, 1);
      break;
    }
  }
  
  var select = v1packageitemselect.instance();
  select.title = (attribute && attribute.name) ? attribute.name : '';
  select.value = (option && option.name) ? option.name : '';
  item.selects[item.selects.length] = select;
  
  MiscUtils.sort(item.selects, ['title']);
};

DlmanageUtils.purchaseChoose = function(item, attribute, option) {
  for (var i = 0, il = item.selects.length; i < il; i++) {
    var select = item.selects[i];
    if (select.title == attribute.name) {
      item.selects.splice(i, 1);
      break;
    }
  }
  var select = v1purchaseitemselect.instance();
  select.title = (attribute && attribute.name) ? attribute.name : '';
  select.value = (option && option.name) ? option.name : '';
  item.selects[item.selects.length] = select;
  
  MiscUtils.sort(item.selects, ['title']);
};

DlmanageUtils.produceChoose = function(item, attribute, option) {
  for (var i = 0, il = item.pi_selects.length; i < il; i++) {
    var select = item.pi_selects[i];
    if (select.title == attribute.name) {
      item.pi_selects.splice(i, 1);
      break;
    }
  }
  var select = ProduceSelect.instance();
  select.produce_trackId = item.trackId;
  select.title = (attribute && attribute.name) ? attribute.name : '';
  select.value = (option && option.name) ? option.name : '';
  item.pi_selects[item.pi_selects.length] = select;
  
  MiscUtils.sort(item.pi_selects, ['title']);
};

/**
 * 找出套餐的原价
 */
DlmanageUtils.original = function(package) {
  if (package) {
    var original = 0;
    for (var i = 0, il = package.packageItems.length; i < il; i++) {
      var price = package.packageItems[i].quantity * package.packageItems[i].sample.price;
      original += parseFloat(price);
    }
    
    if (package.makeup != '') {
      var price = (package.makeup == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_MAKEUP_AT_STUDIO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') ? '<?php echo ((is_array($_tmp=@CUSTOM_PRICE_MAKEUP_AT_STUDIO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' : (package.makeup == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_MAKEUP_AT_HOME)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') ? '<?php echo ((is_array($_tmp=@CUSTOM_PRICE_MAKEUP_AT_HOME)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' : '<?php echo ((is_array($_tmp=@CUSTOM_PRICE_MAKEUP_FULL_DAY)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
';
      original += parseFloat(price);
    }
    
    for (var i = 0, il = package.persons; i < il; i++) {
      var price = (package.type == '<?php echo ((is_array($_tmp=@PACKAGE_TYPE_PHOTO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') ? '<?php echo ((is_array($_tmp=@CUSTOM_PRICE_PHOTOGRAPHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' : '<?php echo ((is_array($_tmp=@CUSTOM_PRICE_VIDEOGRAPHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' ;
      original += parseFloat(price * package.hours);
    }
    return original;
  }
};

/*
DlmanageUtils.choose = function(product, attribute, option) {
  for (var i = 0, il = product.selects.length; i < il; i++) {
    var select = product.selects[i];
    if (select.title == attribute.name) {
      product.selects.splice(i, 1);
      break;
    }
  }
  var select = ProductSelect.instance();
  select.title = (attribute && attribute.name) ? attribute.name : '';
  select.value = (option && option.name) ? option.name : '';
  product.selects[product.selects.length] = select;
  
  MiscUtils.sort(product.selects, ['title']);
};
*/

/**
 * 根据相册,返回它们设计的信息
 */

DlmanageUtils.congregate1 = function(albums) {
  var page = 0, shape = '', title = ''; 
  for (var i = 0, il = albums.length; i < il; i++) {
    var album = albums[i];
    title += album.sample.name + ((i < (il - 1)) ? ', ' : '');
    for (var j = 0, jl = album.selects.length; j < jl; j++) {
      var select = album.selects[j];
      if (select.title == 'Pages') {
        page = Math.max(page, parseInt(select.value, 10));
      } else if (select.title == '形状') {
        shape = select.value;
      }
    }
  }
  return { title: title, 
           page: page,
           shape: shape
         };
};

DlmanageUtils.congregate2 = function(albums) {
  var page = 0, shape = '', title = ''; 
  for (var i = 0, il = albums.length; i < il; i++) {
    var album = albums[i];
    title += album.name + ((i < (il - 1)) ? ', ' : '');
    for (var j = 0, jl = album.selects.length; j < jl; j++) {
      var select = album.selects[j];
      if (select.title == 'Pages') {
        page = Math.max(page, parseInt(select.value, 10));
      } else if (select.title == '形状') {
        shape = select.value;
      }
    }
  }
  return { title: title, 
           page: page,
           shape: shape
         };
};

DlmanageUtils.congregate3 = function(albums) {
  var page = 0, shape = '', title = ''; 
  for (var i = 0, il = albums.length; i < il; i++) {
    var album = albums[i];
    title += album.pi_name + ((i < (il - 1)) ? ', ' : '');
    for (var j = 0, jl = album.pi_selects.length; j < jl; j++) {
      var select = album.pi_selects[j];
      if (select.title == 'Pages') {
        page = Math.max(page, parseInt(select.value, 10));
      } else if (select.title == '形状') {
        shape = select.value;
      }
    }
  }
  return { title: title, 
           page: page,
           shape: shape
         };
};

DlmanageUtils.congregate4 = function(albums) {
  var page = 0, shape = '', title = ''; 
  for (var i = 0, il = albums.length; i < il; i++) {
    var album = albums[i];
    title += album.name + ((i < (il - 1)) ? ', ' : '');
    for (var j = 0, jl = album.v2_selects.length; j < jl; j++) {
      var select = album.v2_selects[j];
      if (select.title == 'Pages') {
        page = Math.max(page, parseInt(select.value, 10));
      } else if (select.title == '形状') {
        shape = select.value;
      }
    }
  }
  return { title: title, 
           page: page,
           shape: shape
         };
};
/**
 * 把orderTrackId转换成order
 */
DlmanageUtils.order = function(orders, trackId) {
  var p = [], a = [];
  
  for (var i = 0, il = orders.length; i < il; i++) {
    var tmp = orders[i];
    if (tmp.trackId == trackId) {
      return tmp;
    }
  }
  return null;
};

/**
 * Reverse
 */
DlmanageUtils.reverse = function(produce, track) {
  produce.e_oid = track.produce_id;
  produce.id = track.produce_id;
  produce.parent_trackId = track.parent_trackId;
  produce.cancelled = track.cancelled;
  produce.completed = track.completed;
  produce.modified = track.modified;
  produce.state = track.state;
  produce.deadline = track.deadline;

  produce.createdDate = track.createdDate;
  produce.sentDate = track.sentDate;
  produce.receivedDate = track.receivedDate;
  produce.receiver = track.receiver;
  produce.address = track.address;
  produce.code = track.code;
  produce.company = track.company;
  produce.weight = track.weight;
  produce.comment = track.comment;
  produce.review = track.review;
  
  produce.user_trackId = track.user_trackId;
  produce.user_account = track.user_account; 
  produce.user_password = track.user_password;
  produce.user_name = track.user_name;
  produce.user_email = track.user_email;
  produce.user_type = track.user_type;
  
  produce.when = track.when;
  produce.how = track.how;
  
  return produce;
};

/**
 * Track流程中的操作
 */
DlmanageUtils.getTrack = function(produce, user, date, transition, extra) {
  var track = ProduceTrack.instance();
  
  track.produce_id = produce.id;
  track.parent_trackId = produce.parent_trackId;
  track.cancelled = produce.cancelled;
  track.completed = produce.completed;
  track.modified = produce.modified;
  track.state = produce.state;
  track.deadline = produce.deadline;
  
  track.createdDate = produce.createdDate;
  track.sentDate = produce.sentDate;
  track.receivedDate = produce.receivedDate;
  track.receiver = produce.receiver;
  track.address = produce.address;
  track.code = produce.code;
  track.company = produce.company;
  track.weight = produce.weight;
  track.comment = produce.comment;
  track.review = produce.review;
  
  track.user_trackId = produce.user_trackId;
  track.user_account = produce.user_account; 
  track.user_password = produce.user_password;
  track.user_name = produce.user_name;
  track.user_email = produce.user_email;
  track.user_type = produce.user_type;
  
  track.when = MiscUtils.clone(produce.when);
  track.how = produce.how;
  track.date = date;
  track.userTrackId = user.trackId;
  track.userAccount = user.account;
  track.sourceId = (transition) ? transition.source.id : 0;
  track.targetId = (transition) ? transition.target.id : 0;
  track.extra = extra;
  return track;
};

DlmanageUtils.getTrackUser = function(produce, track) {
  trackUsers = [];
  for (var i = 0, il = produce.pUsers.length; i < il; i++) {
    var pu = produce.pUsers[i];
    var pTrackUser = ProduceTrackUser.instance();
    pTrackUser.trackId = pu.trackId;
    pTrackUser.track_trackId = track.trackId;
    pTrackUser.account = pu.account;
    pTrackUser.password = pu.password;
    pTrackUser.name = pu.name;
    pTrackUser.email = pu.email;
    pTrackUser.type = pu.type;
    trackUsers[trackUsers.length] = pTrackUser;
  }
  return trackUsers;
};

DlmanageUtils.getProduceUser = function(produce, track) {
  var produceUsers = [];
  for (var i = 0, il = track.pUsers.length; i < il; i++) {
    var tu = track.pUsers[i];
    var pUser = ProduceUser.instance();
    pUser.trackId = tu.trackId;
    pUser.produce_id = produce.id;
    pUser.account = tu.account;
    pUser.password = tu.password;
    pUser.name = tu.name;
    pUser.email = tu.email;
    pUser.type = tu.type;
    produceUsers[produceUsers.length] = pUser;
  }
  return produceUsers;
};

/**
 * 记录流程中的操作
 */
DlmanageUtils.record = function(produce, user, date, transition, extra, overdueReason) { 
  var event = ProduceEvent.instance();
  event.produce_trackId = produce.trackId;
  event.date = date;
  event.userAccount = user.account;
  event.sourceId = (transition) ? transition.source.id : 0;
  event.targetId = (transition) ? transition.target.id : 0;
  event.extra = (extra) ? extra : '';
  event.isExpired = (parseInt((SimpleDate.toStamp(produce.deadline) - SimpleDate.toStamp(date)) / 86400, 10) < 0) ? 1 : 0;
  event.overdueReason = (overdueReason) ? overdueReason : '';
  return event;
};

/**
 * 处理流程过渡
 */

DlmanageUtils.transit = function(transition, produce, date) {
  produce.state = transition.target.id;
  if (transition.mode == DlmanageUtils.normal) {
    produce.deadline = SimpleDate.forward(date, transition.length * 86400);
  } else if (transition.mode == DlmanageUtils.dop) {
    produce.deadline = SimpleDate.forward(produce.date, transition.length * 86400);
  } else if (transition.mode == DlmanageUtils.mixed) {
    produce.deadline = ((SimpleDate.toStamp(date) + transition.length * 86400) < SimpleDate.toStamp(produce.deadline)) ? produce.deadline : SimpleDate.forward(date, transition.length * 86400);
  } else if (transition.mode == DlmanageUtils.none) {
    produce.deadline = null;
    produce.completed = true;
  }
};

/**
 * 处理操作1（默认,无任何其它措施）
 */
DlmanageUtils.operate = function(transition, pos, callbackFunc, produce, user, date, options) {
  var produceUsers = (options && options.preconUsers) ? options.preconUsers : [];
  var object = (options && options._object) ? options._object : null;
  var trackUsers = [];
  
//自动发工资功能
//  if ((produce.state == 4 && produce.pi_model == '<?php echo ((is_array($_tmp=@MODEL_NAME_USER_PHOTOGRAPHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') || (produce.state == 4 && produce.pi_model == '<?php echo ((is_array($_tmp=@MODEL_NAME_USER_VIDEOGRAPHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
')) {
//    new RequestUtils()._read('customer', null, 'd.oid = ' + produce.customerId, null, null, null, null, function(result, params) { DlmanageUtils.findUser(result.data[0], transition, produce, user, date, options); }, null);
//  }
  
  var t = this.getTrack(((options && options.previous) ? options.previous : produce), user, date, transition, ((options && options.extra) ? ' ' + options.extra : ''));
  var e = this.record(produce, user, date, transition, ((options && options.extra) ? options.extra : null), ((options && options.overdueReason) ? options.overdueReason : null));
  this.transit(transition, produce, date);
  
  if (object) {
    var events = object.e;
    var tracks = object.t;
    var produces = object.p;
    produces[produces.length] = produce;
    new RequestUtils()._write2([{ n: 'produce', a: produces, r: [] }, { n: 'produceevent', a: events, r: [] }, { n: 'producetrack', a: tracks, r: []} ], callbackFunc, { php: Constant.FACTORY + '/customphp/mysqlwrite2.php', pos: pos });
    return;
  }
  
  if (produce.pi_model == '<?php echo ((is_array($_tmp=@MODEL_NAME_PRECON)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
    trackUsers = this.getTrackUser(produce, t);
    new RequestUtils()._write2([{ n: 'produce', a: [produce], r: [] }, { n: 'produceevent', a: [e], r: [] }, { n: 'producetrack', a: [t], r: []}, { n: 'produceuser', a: produceUsers, r: []}, { n: 'producetrackuser', a: trackUsers, r: []} ], callbackFunc, { php: Constant.FACTORY + '/customphp/mysqlwrite2.php', pos: pos });
  } else {
    new RequestUtils()._write2([{ n: 'produce', a: [produce], r: [] }, { n: 'produceevent', a: [e], r: [] }, { n: 'producetrack', a: [t], r: []}], callbackFunc, { php: Constant.FACTORY + '/customphp/mysqlwrite2.php', pos: pos });
  }
};


/**
 * 处理操作2（所有的摄影师完成流程后,生成摄影产品和设计产品 & 设计流程完成后,生成相册产品）
 */
DlmanageUtils.operate2 = function(transition, pos, callbackFunc, produce, user, date, options) {
  new RequestUtils()._read('v1myorder', null, 'oid = ' + produce.orderId, null, null, null, null, function(result, params) { DlmanageUtils.operate2produces(result.data[0], transition, pos, callbackFunc, produce, user, date, options); }, { php: produce.host + '/customphp/mysqlread.php', pos: pos });
};

/**
 * 处理操作2-2（Customer Takes Photo CD,检查付款）
 */
DlmanageUtils.operate2produces = function(order, transition, pos, callbackFunc, produce, user, date, options) {
  if (options && options.stage) {
    if (!this.debt(order, options.stage)) {
      callbackFunc();
      return;
    }
  }
  var joins = '&selects=1' + '&purchaseitems=1' + '&preconusers=0' + '&events=1' + '&tracks=0' + '&produces=0' + '&notes=0';
  var args = '&c=d.branch = \'' + produce.branch + '\' AND d.orderId = ' + produce.orderId + joins;
  new RequestUtils()._mysql('produce', args, function(result, params) { DlmanageUtils.operate2generate(order.purchaseItems, result.data, transition, pos, callbackFunc, produce, user, date, options);}, { php: Constant.FACTORY + '/customphp/produceread.php', pos: pos });
};

/**
 * 处理操作2-3
 */
DlmanageUtils.operate2generate = function(purchases, produces, transition, pos, callbackFunc, produce, user, date, options) {

  var found = MiscUtils.find(produces, [{ attrs: ['trackId'], value: produce.trackId }]);
  if (found.length != 1) {
    window.alert('ERROR: THE PRODUCE IS NOT FOUND');
    return;
  }
  produce = found[0];
  
  var t = this.getTrack(((options && options.previous) ? options.previous : produce), user, date, transition, ((options && options.extra) ? ' ' + options.extra : ''));
  var e = this.record(produce, user, date, transition, ((options && options.extra) ? options.extra : null), ((options && options.overdueReason) ? options.overdueReason : null));
  this.transit(transition, produce, date);
  var result = this.synchronise(purchases, produces, options);
  this.submit2(result, callbackFunc, pos, {e: e, t: t});
};

/**
 * 处理流操作3（Remind Assingee,检查付款&检查Ceremony Locations和Reception Locations）
 */
DlmanageUtils.operate3 = function(transition, pos, callbackFunc, produce, user, date, options) {
  /*new RequestUtils()._read('customer', null, 'd.oid = ' + produce.customerId, null, null, null, null, function(result, params) { DlmanageUtils.operate3check(result.data[0], transition, pos, callbackFunc, produce, user, date, options); }, { pos: pos });
*/
   var args = '&oid=' + produce.customerId; 
  new RequestUtils()._mysql('v1customer', args, function(result, params) { DlmanageUtils.operate3check(result.data[0], transition, pos, callbackFunc, produce, user, date, options); }, {php:'customphp/mysqlread.php'});  
};

/**
 * 处理流操作3-2
 */
DlmanageUtils.operate3check = function(customer, transition, pos, callbackFunc, produce, user, date, options) {
  var div, order = this.order(customer.orders, produce.orderTrackId), popupBox = new PopupBox(), _self = this;
  if (!this.debt(order, ((options && options.stage) ? options.stage : null))) {
    callbackFunc();
    return;
  }
  var func = function() { //自动发工资功能
                          //if (produce.pi_model == '<?php echo ((is_array($_tmp=@MODEL_NAME_USER_MAKEUP)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' || produce.pi_model == '<?php echo ((is_array($_tmp=@MODEL_NAME_USER_LIGHT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
                            //DlmanageUtils.findUser(customer, transition, produce, user, date, options);
                          //}
                          var t = DlmanageUtils.getTrack(((options && options.previous) ? options.previous : produce), user, date, transition, ((options && options.extra) ? ' ' + options.extra : ''));
                          var e = DlmanageUtils.record(produce, user, date, transition, ((options && options.extra) ? options.extra : null), ((options && options.overdueReason) ? options.overdueReason : null));
                          DlmanageUtils.transit(transition, produce, date);
                          DlmanageUtils.submit1([produce], [e], [t], callbackFunc, pos);
                        };
  if (order.type == '<?php echo ((is_array($_tmp=@ORDER_TYPE_WEDDING)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
    if ((customer.ceremony == '' || customer.reception == '') && (options && options.func)) {
      div = document.createElement('div');
      var func1 = function() { if (customer.ceremony == '' || customer.reception == '') {
                                 window.alert('Ceremony OR Reception IS EMPTY');
                                 return;
                               }
                               popupBox._close();
                               new RequestUtils()._mwrite('v1customer', [customer], [], function() { func(); }, { pos: pos });
                             }
      MiscUtils.dialog(popupBox, pos, div, func1, function() { popupBox._close(); });
      options.func(div, customer, options);
      return;
    }
  }
  func();
};

/*自动发工资功能
DlmanageUtils.findUser = function(customer, transition, produce, user, date, options) {
  new RequestUtils()._read('user', null, 'd.account =\'' + produce.user_account + '\'', null, null, null, null, function(result, params) { DlmanageUtils.expense(result.data[0], customer, transition, produce, user, date, options); }, null);
};

DlmanageUtils.expense = function(u, customer, transition, produce, user, date, options) {
  var order = this.order(customer.orders, produce.orderTrackId), _self = this;
  var exp = Expense.instance();
  exp.createdDate = date;
  exp.payDate = date;
  exp.payee = u.account;
  if (produce.pi_model == '<?php echo ((is_array($_tmp=@MODEL_NAME_USER_MAKEUP)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
    exp.particular = 'Wage (Dresser)';
    if (produce.pi_type == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_MAKEUP_AT_HOME)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      exp.amount = u.skill.mHouse * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.mHouse + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;
    } else if (produce.pi_type == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_MAKEUP_AT_STUDIO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      exp.amount = u.skill.mStudio * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.mStudio + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;
    } else {
      exp.amount = u.skill.mFullDay * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.mFullDay + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;
    }
  } else if (produce.pi_model == '<?php echo ((is_array($_tmp=@MODEL_NAME_USER_LIGHT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
    exp.particular = 'Wage (Lighting Assistant)';
    exp.amount = u.skill.lightingRate * (parseInt(produce.estimates) + parseInt(produce.extras));
    exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.lightingRate + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;
  } else if (produce.pi_model == '<?php echo ((is_array($_tmp=@MODEL_NAME_USER_PHOTOGRAPHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
    exp.particular = 'Wage (Photographer)';
    if (order.type == '<?php echo ((is_array($_tmp=@ORDER_TYPE_WEDDING)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      exp.amount = u.skill.pWedding * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.pWedding + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;

    } else if (order.type == '<?php echo ((is_array($_tmp=@ORDER_TYPE_PREWEDDING)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      exp.amount = u.skill.pPrewedding * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.pPrewedding + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;

    } else if (order.type == '<?php echo ((is_array($_tmp=@ORDER_TYPE_ENGAGEMENT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      exp.amount = u.skill.pEngagement * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.pEngagement + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;

    } else if (order.type == '<?php echo ((is_array($_tmp=@ORDER_TYPE_PORTRAIT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      exp.amount = u.skill.pPortrait * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.pPortrait + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;

    } else {
      exp.amount = 0;
    }
  } else if (produce.pi_model == '<?php echo ((is_array($_tmp=@MODEL_NAME_USER_VIDEOGRAPHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
    exp.particular = 'Wage (Videographer)';
    if (order.type == '<?php echo ((is_array($_tmp=@ORDER_TYPE_WEDDING)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      exp.amount = u.skill.vWedding * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.vWedding + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;

    } else if (order.type == '<?php echo ((is_array($_tmp=@ORDER_TYPE_PREWEDDING)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      exp.amount = u.skill.vPrewedding * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.vPrewedding + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;

    } else if (order.type == '<?php echo ((is_array($_tmp=@ORDER_TYPE_ENGAGEMENT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      exp.amount = u.skill.vEngagement * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.vEngagement + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;

    } else if (order.type == '<?php echo ((is_array($_tmp=@ORDER_TYPE_PORTRAIT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      exp.amount = u.skill.vPortrait * (parseInt(produce.estimates) + parseInt(produce.extras));
      exp.note = 'customerNo: ' + customer.id + ', ' + 'orderType: ' + order.flag + ', ' + 'Amount: ' + u.skill.vPortrait + ' x ' + (parseInt(produce.estimates) + parseInt(produce.extras)) + ' = ' + exp.amount;

    } else {
      exp.amount = 0;
    }
  }
  exp.userTrackId = user.trackId;
  exp.userAccount = user.account;
  exp.cancelledDate = null;
  exp.confirmDate = null;
  new RequestUtils()._write('expense', [exp], [], function() { }, null);
};
*/
DlmanageUtils.debt = function(order, stage) {
  var stage, rules, rule, received;
  rules = this.payment(order.type);
  if (!rules) {
    window.alert('NO PROPER PAYMENT SOLUTION FOR ' + order.type);
    return;
  }
  stage = (stage) ? stage - 1 : rules.length - 1;
  
  rule = (rules[stage]) ? rules[stage] : rules[rules.length - 1];
  
  received = 0
  for (var i = 0, il = order.payments.length; i < il; i++) {
    var p = order.payments[i];
    if (p.cancelled == 1) {
      continue;
    }
    received += parseFloat(p.amount, 10);
  }
  if ( parseFloat( (order.price * rule.rate * (parseFloat(1) + parseFloat('<?php echo ((is_array($_tmp=@GST)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'))).toFixed(2) ) > parseFloat( received.toFixed(2) )) {
    var str = 'BALANCE: - $(' + (Math.abs((received - (order.price * rule.rate)).toFixed(2)).toFixed(2) + ' + ' + parseFloat(Math.abs(((order.price * rule.rate)).toFixed(2)) * parseFloat('<?php echo ((is_array($_tmp=@GST)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
')).toFixed(2) + 'GST)') + ', CONTINUE?\n';
    var r = window.confirm(str);
    if (!r) {
      return false;
    }
  }
  return true
};

/**
 * 把进程添加到工厂端
 */
DlmanageUtils.submit = function(produces, callbackFunc, pos) {
  var updates = MiscUtils.find(produces, [{ attrs: ['_deleted'], value: undefined }]);
  var removes = MiscUtils.find(produces, [{ attrs: ['_deleted'], value: true }, { attrs: ['id'], value: undefined, unequal: true }]);
  new RequestUtils()._write('produce', updates, removes, callbackFunc, { php: Constant.FACTORY + '/customphp/mysqlwrite.php', pos: pos });
};

DlmanageUtils.submit1 = function(produces, events, tracks, callbackFunc, pos) {
  var updates = MiscUtils.find(produces, [{ attrs: ['_deleted'], value: undefined }]);
  var removes = MiscUtils.find(produces, [{ attrs: ['_deleted'], value: true }, { attrs: ['id'], value: undefined, unequal: true }]);
  new RequestUtils()._write2([{ n: 'produce', a: updates, r: removes }, { n: 'produceevent', a: events, r: [] }, { n: 'producetrack', a: tracks, r: [] }], callbackFunc, { php: Constant.FACTORY + '/customphp/mysqlwrite2.php', pos: pos });
};

DlmanageUtils.submit2 = function(result, callbackFunc, pos, options) {
  var event = (options && options.e) ? options.e : null;
  var track = (options && options.t) ? options.t : null;
  var updates = MiscUtils.find(result.produces, [{ attrs: ['_deleted'], value: undefined }]);
  var removes = MiscUtils.find(result.produces, [{ attrs: ['_deleted'], value: true }, { attrs: ['id'], value: undefined, unequal: true }]);
  
  var updateNotes = [];
  var removeNotes = [];
  var updateNotes = MiscUtils.find(result.notes, [{ attrs: ['_deleted'], value: undefined }]);
  var removeNotes = MiscUtils.find(result.notes, [{ attrs: ['_deleted'], value: true }]);
  
  if (options) {
    result.events[result.events.length] = event;
    new RequestUtils()._write3([{ n: 'produce', a: updates , r: removes }, { n: 'produceselect', a: result.produceSelects, r: [] }, { n: 'produceevent', a: result.events, r: [] }, { n: 'producetrack', a: [track], r: [] }, { n: 'producepurchaseitem', a: result.purchaseItems, r: [] }, { n: 'producepurchaseitemselect', a: result.purchaseItemSelects, r: [] }, { n: 'producenote', a: updateNotes, r: removeNotes }], callbackFunc, { php: Constant.FACTORY + '/customphp/mysqlwrite3.php', pos: pos });
  } else {
    new RequestUtils()._write3([{ n: 'produce', a: updates , r: removes }, { n: 'produceselect', a: result.produceSelects, r: [] }, { n: 'produceevent', a: result.events, r: [] }, { n: 'producepurchaseitem', a: result.purchaseItems, r: [] }, { n: 'producepurchaseitemselect', a: result.purchaseItemSelects, r: [] }, { n: 'producenote', a: updateNotes, r: removeNotes }], callbackFunc, { php: Constant.FACTORY + '/customphp/mysqlwrite3.php', pos: pos });
  }
};

/**
 * 把每一个进程补充完整
 */
DlmanageUtils.patch = function(produces, customer) {
  for (var i = 0, il = produces.length; i < il; i++) {
    var tmp = produces[i];

    var order = this.order(customer.orders, tmp.orderTrackId);
    if (!order) {
      continue;
    }
    tmp.orderFlag = order.flag;
    tmp.orderId = order.id;
    tmp.customerId = customer.id;
  }
};

/**
 * 重新命名（摄影师、摄像师、化妆师）。
 */
DlmanageUtils.rename = function(produces) {
  var count = {};
  for (var i = 0, il = produces.length; i < il; i++) {
    var produce = produces[i];
    if (produce._deleted) {
      continue;
    }
    if (count[produce.pi_model] == undefined) {
      count[produce.pi_model] = 1;
    } else {
      count[produce.pi_model]++;
    }
    produce.title = produce.pi_model + ' ' + count[produce.pi_model];
  }
};

/**
 * 比较产品和流程
 */
DlmanageUtils.compare = function(purchases, produces) {
  for (var i = 0, il = purchases.length; i < il; i++) {
    var purchase = purchases[i];
    purchase._added = false;
  }
  for (var i = 0, il = produces.length; i < il; i++) {
    var produce = produces[i];
    produce._exist = false;
  }
    
  for (var i = 0, il = purchases.length; i < il; i++) {
    var purchase = purchases[i];
    for (var j = 0, jl = produces.length; j < jl; j++) {
      var produce = produces[j];
      if (purchase.trackId == produce.pi_trackId) {
        purchase._added = true;
        produce._exist = true;
      }
    }
  }
};

/**
 * 添加/更新purchase和produce的note
 */
DlmanageUtils.updateSystemNote = function(customer, result, options) {
  var user = (options && options.user) ? options.user : null;
  var date = (options && options.date) ? options.date : null;
  
  for (var m = 0, ml = customer.orders.length; m < ml; m++) {
    var order = customer.orders[m];
    var content = '[SYSTEM] \n Photo Package: ' + ((order.photoname != '') ?  order.photoname : 'none') + ',\n Video Package: ' + ((order.videoname != '') ?  order.videoname : 'none') + ',\n Bride: ' + ((customer.bridename != '') ? customer.bridename : 'none') + ', Groom: ' + ((customer.groomname != '') ? customer.groomname : 'none') + ',\n Wedding Day: ' + ((order.date) ?  SimpleDate.format(order.date) : 'To be confirmed');
    var conditions = [{ attrs: ['orderTrackId'], value: order.trackId }, { attrs: ['_deleted'], value: undefined }, { attrs: ['cancelled'], value: 0 }];

    for (var n = 0, nl = order.purchaseItems.length; n < nl; n++) {
      var pur = order.purchaseItems[n];
      if (!pur.id) {
        var note = v1purchasenote.instance();
        note.author = user.account;
        note.date = date;
        note.content = content;
        pur.notes[pur.notes.length] = note;
      } else {
        for (var k = 0, kl = pur.notes.length; k < kl; k++) {
           
          var no = pur.notes[k];
          if (no.content.indexOf('[SYSTEM]') != -1) {
            no.content = content;
          }
        }
      }
    }
    
    var pros = MiscUtils.find(result.produces, conditions);

    for (var i = 0, il = pros.length; i < il; i++) {
      var p = pros[i];
      if (!p.id) {
        var nt = ProduceNote.instance();
        nt.author = user.account;
        nt.date = date;
        nt.content = content;
        nt.produce_trackId = p.trackId;
        result.notes[result.notes.length] = nt;
      } else {
        var notes = MiscUtils.find(p.v2_notes, [{attrs: ['produce_trackId'], value: p.trackId}]);
        if (notes.length == 0) {
          var nt = ProduceNote.instance();
          nt.author = user.account;
          nt.date = date;
          nt.content = content;
          nt.produce_trackId = p.trackId;
          result.notes[result.notes.length] = nt;
        } else {
          exist = false;
          for (var j = 0, jl = notes.length; j < jl; j++) {
            var nn = notes[j];
            if (nn.content.indexOf('[SYSTEM]') == -1) {
              continue;
            }
            if (nn.content.indexOf('(INHERIT)[SYSTEM]') != -1) {
              nn._deleted = true;
              var nt = ProduceNote.instance();
              nt.author = user.account;
              nt.date = date;
              nt.content = '(INHERIT)' + content;
              nt.produce_trackId = p.trackId;
              result.notes[result.notes.length] = nn;
              result.notes[result.notes.length] = nt;
            } else if (nn.content.indexOf('[SYSTEM]') != -1) {
              nn._deleted = true;
              var nt = ProduceNote.instance();
              nt.author = user.account;
              nt.date = date;
              nt.content = content;
              nt.produce_trackId = p.trackId;
              result.notes[result.notes.length] = nn;
              result.notes[result.notes.length] = nt;
            } else {
              var nt = ProduceNote.instance();
              nt.author = user.account;
              nt.date = date;
              nt.content = content;
              nt.produce_trackId = p.trackId;
              result.notes[result.notes.length] = nt;
            }
          }
        }
      }
    }
  }
};

/**
 * 根据产品生成流程
 */
DlmanageUtils.generate = function(purchase, options) {
  var n = [];
  var e = [];
  var s = []; //（这个其实是ps）
  
  var produce = Produce.instance();
  produce.pi_selects = [];
  produce.v2_pUsers = [];
  produce.v2_purchaseItems = [];
  produce.v2_events = [];
  produce.v2_tracks = [];
  produce.v2_produces = [];
  produce.v2_notes = [];
  
  produce.branch = (options && options.branch) ? options.branch : Constant.BRANCH;
  produce.host = (options && options.host) ? options.host : 'http://<?php echo ((is_array($_tmp=@DOMAIN)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
<?php echo ((is_array($_tmp=@PATH)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
';
  produce.state = (options && options.state) ? options.state : 0;
  produce.deadline = (options && options.deadline) ? options.deadline : null;
  produce.title = purchase.name;

  produce.user_trackId = (options && options.user_trackId) ? options.user_trackId : '';
  produce.user_account = (options && options.user_account) ? options.user_account : '';
  produce.user_password = (options && options.user_password) ? options.user_password : '';
  produce.user_name = (options && options.user_name) ? options.user_name : '';
  produce.user_email = (options && options.user_email) ? options.user_email : '';
  produce.user_type = (options && options.user_type) ? options.user_type : '';
  
  produce.when = null;

  produce.pi_trackId = purchase.trackId;
  produce.pi_sampleId = purchase.sampleId;
  produce.pi_name = purchase.name;
  produce.pi_price = purchase.price;
  produce.pi_unit = purchase.unit;
  produce.pi_type = purchase.type;
  produce.pi_model = purchase.model;
  produce.pi_otherId = purchase.otherId;
  produce.pi_quantity = purchase.quantity;
  produce.pi_total = purchase.total;
  produce.pi_packageInc = purchase.packageInc;
  
  for (var i = 0, il = purchase.selects.length; i < il; i++) {
    var ps = purchase.selects[i];
    var sel = ProduceSelect.instance();
    sel.produce_trackId = produce.trackId;
    sel.title = ps.title;
    sel.value = ps.value;
    s[s.length] = sel;
    produce.pi_selects[produce.pi_selects.length] = sel;
  }
  
  for (var k = 0, kl = purchase.notes.length; k < kl; k++) {
    var no = purchase.notes[k];
    var pn = ProduceNote.instance();
    pn.produce_trackId = produce.trackId;
    pn.author = no.author;
    pn.date = no.date;
    pn.content = '(INHERIT)' + no.content;
    pn.cancelled = no.cancelled;
    n[n.length] = pn;
    produce.v2_notes[produce.v2_notes.length] = pn;
  }
  
  produce.date = (options && options.date) ? options.date : null;
  if (produce.pi_model == Constant.MODEL_NAME_USER_PHOTOGRAPHER || produce.pi_model == Constant.MODEL_NAME_USER_VIDEOGRAPHER || produce.pi_model == Constant.MODEL_NAME_USER_MAKEUP || produce.pi_model == Constant.MODEL_NAME_USER_LIGHT) {
    produce.title = purchase.model;
    produce.estimates = purchase.quantity;
  }
  if (options && options.events) {
    for (var j = 0, jl = options.events.length; j < jl; j++) {
      var tmp = options.events[j];
      tmp = this.reproduce(tmp);
      tmp.produce_trackId = produce.trackId;
      e[e.length] = tmp;
      produce.v2_events[produce.v2_events.length] = tmp
    }
  }
  produce.orderFlag = (options && options.orderFlag) ? options.orderFlag : '';
  produce.orderTrackId = (options && options.orderTrackId) ? options.orderTrackId : '';
  produce.orderId = (options && options.orderId) ? options.orderId : 0;
  produce.customerId = (options && options.customerId) ? options.customerId : 0;
  
  return { p: produce,
           s: s,
           e: e,
           n: n
         };
};

/**
 * 同步产品和流程，这里的produces一定要有各种原来的属性
 * { ...
 *   pi_selects
 *   v2_purchaseItems
 *   v2_pUsers
 *   v2_events
 *   v2_tracks
 *   v2_produces
 *   v2_notes
 * }
 */
DlmanageUtils.synchronise = function(purchases, produces, options) {
  var tmp, tmp2, tmp3, tmp4, avlPurchases, avlProduces, result;
  
  //检查options
  if (!options){
    options = {};
  }

  //6个数组：（添加/更新/删除）： *produces, （添加/更新）：ps, e, n, pi, s （还缺2个：deleted pi, deleted s）
  //###应对多次运行synchronise###
  //produces
  var ps = (options.result) ? options.result.produceSelects : [];
  var e = (options.result) ? options.result.events : [];
  var n = (options.result) ? options.result.notes : [];
  var pi = (options.result) ? options.result.purchaseItems : [];
  var s = (options.result) ? options.result.purchaseItemSelects : [];
  
  var orderDate = (options.orderDate) ? options.orderDate : null;
  var user = (options.user) ? options.user : ProduceUser.instance();
  var date = (options.date) ? options.date : null;
  var orderFlag = (options.orderFlag) ? options.orderFlag : '';
  var orderTrackId = (options.orderTrackId) ? options.orderTrackId : '';
  var orderId = (options.orderId) ? options.orderId : 0;
  var customerId = (options.customerId) ? options.customerId : 0;
  
  avlPurchases = MiscUtils.find(purchases, [{ attrs: ['cancelled'], value: 0 }]);
  avlProduces = MiscUtils.find(produces, [{ attrs: ['cancelled'], value: 0 }, { attrs: ['_deleted'], value: undefined }, { attrs: ['orderTrackId'], value: orderTrackId }]);
  this.compare(avlPurchases, avlProduces);

  /* Remove produces for the deleted purchases */
  for (var i = 0, il = avlProduces.length; i < il; i++) {
    var tmp = avlProduces[i];
    if (tmp.pi_model == Constant.MODEL_NAME_ALBUM_DESIGN) {
      var j = 0;
      while (j < tmp.v2_purchaseItems.length) {
        var tmp2 = tmp.v2_purchaseItems[j];
        var exist = false;
        for (var k = 0, kl = avlPurchases.length; k < kl; k++) {
          var tmp3 = avlPurchases[k];
          if (tmp3.otherId != tmp.pi_trackId) {
            continue;
          }
          if (tmp2.trackId == tmp3.trackId) {
            exist = true;
          }
        }
        if (!exist) {
          MiscUtils.remove(tmp.v2_purchaseItems, tmp2, 'trackId');
          if (tmp.v2_purchaseItems.length == 0) {
            tmp._deleted = true;
          }
          j = 0;
        }
        j++;
      }
    } else if (tmp.pi_model != Constant.MODEL_NAME_PRECON && tmp.pi_model != Constant.MODEL_NAME_MUSIC && tmp.pi_model != Constant.MODEL_NAME_REQUIREMENT) {
      if (!tmp._exist) {
        if (tmp.id) {
          tmp.cancelled = 1;
        } else {
          tmp._deleted = true;
        }
      }
    }
  }
  
  //以下的代码，主要负责添加新产品。
  //处理动作包括：添加/更新 produces, ps, pi, s, 添加e, n, 添加v2_events, v2_notes, 添加/更新 v2_purchaseItem, pi_select
  //###如果是添加问题，就要检查以下的代码###
  //produces里面删过产品，因此要更新avlPurchases, avlProduces
  avlPurchases = MiscUtils.find(purchases, [{ attrs: ['cancelled'], value: 0 }]);
  avlProduces = MiscUtils.find(produces, [{ attrs: ['cancelled'], value: 0 }, { attrs: ['_deleted'], value: undefined }, { attrs: ['orderTrackId'], value: orderTrackId }]);
  this.compare(avlPurchases, avlProduces);
  
  //添加产品，是要根据不同的情况。因此第一件事情是把所有的情况总结出来
  //【1】所有的摄影师
  var total = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_PHOTOGRAPHER }]);
  //【2】所有没完成的摄影师
  var completed = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_PHOTOGRAPHER }, { attrs: ['state'], value: 7, unequal: true }]);
  //【3】所有的摄像师
  var vtotal = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_VIDEOGRAPHER }]);
  //【4】所有没完成的摄像师
  var vcompleted = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_VIDEOGRAPHER }, { attrs: ['state'], value: 9, unequal: true }]);
  //【5】已完成的录像音乐
  var vmusic = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_MUSIC }, { attrs: ['state'], value: 3 }]);
  //【6】已完成的录像要求表格
  var vrequirement = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_REQUIREMENT }, { attrs: ['state'], value: 3 }]);
  //【7】已完成的录像剪辑
  var vedit = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_PRODUCT_VIDEO }, { attrs: ['state'], value: 12 }]);
  //【8】已完成的Blu Ray录像剪辑
  var veditbr = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_PRODUCT_VIDEO_BLURAY }, { attrs: ['state'], value: 12 }]);
  //【9】所有的精修照片
  var retouch = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_PRODUCT_RETOUCH }]);
  //【10】有任何一个精修照片已经完成了
  var rready = false;
  for (var i = 0, il = retouch.length; i < il; i++) {
    var tmp = retouch[i];
    if (tmp && tmp.state > 11) {
        rready = true;
    }
  }
  
  //开始按照产品循环，因为已经做过compare（如果_add为false就代表未添加的产品。详情参考function compare）
  for (var i = 0, il = avlPurchases.length; i < il; i++) {
    tmp = avlPurchases[i];
    //产品分为：1非录像产品，2录像产品
    if (tmp.model != Constant.MODEL_NAME_PRODUCT_VIDEO && tmp.model != Constant.MODEL_NAME_PRODUCT_VIDEODVD && tmp.model != Constant.MODEL_NAME_PRODUCT_VIDEO_BLURAY && tmp.model != Constant.MODEL_NAME_PRODUCT_VIDEODVD_BLURAY) {
      //处理相册（普通和杂志）产品：如果摄影师总数大于0，没完成摄影师数等于0（=摄影师都完成了）。不然就不管。
      if ((total.length > 0 && completed.length == 0) && ((tmp.type == Constant.SAMPLE_TYPE_ALBUM || tmp.type == Constant.SAMPLE_TYPE_MAGAZINE) && tmp.model == Constant.MODEL_NAME_PRODUCT_COMMON)) {
        //【第一步】检查设计，根据情况处理：
        //1 如果有相关设计，那么要把相册加入到该设计包含的相册中去
        //2 如果该设计完成了，那么要生成相册流程（不然就不用管了，等设计完成会同步的）
        //3 如果没有设计，就要生成设计流程。
        
        //existed = 该相册是否有设计
        var existed = false;
        //找出所有的设计，开始做循环
        var designs = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_ALBUM_DESIGN }]);
        for (var j = 0, jl = designs.length; j < jl; j++) {
          var tmp2 = designs[j];
          //如果该相册属于该设计
          if (tmp2.pi_trackId == tmp.otherId) {
            //先检查该设计是否已经包含该相册了，用到 v2_purchaseItems
            var included = false;
            for (var k = 0, kl = tmp2.v2_purchaseItems.length; k < kl; k++) {
              var tmp3 = tmp2.v2_purchaseItems[k];
              if (tmp3.trackId == tmp.trackId) {
                included = true;
              }
            }
            //如果不包含，那么把相册加入该设计
            if (!included) {
              var purchaseItem = this.renew(tmp);
              var selects = this.renew(tmp.selects);
              var sels = [];
              for (var ii = 0, iil = selects.length; ii < iil; ii++) {
                var sel = selects[ii];
                sel.purchase_trackId = purchaseItem.trackId;
                s[s.length] = sel;
                sels[sels.length] = sel;
              }
              purchaseItem.produce_trackId = tmp2.trackId;
              purchaseItem.v2_selects = sels;
              pi[pi.length] = purchaseItem;
              tmp2.v2_purchaseItems[tmp2.v2_purchaseItems.length] = purchaseItem;
            }
            //如果该设计已经完成了，那么创建相册流程
            if (tmp2.completed == 1 && !tmp._added) {
              MiscUtils.sort(tmp2.v2_events, ['id']);
              options.state = 13;
              options.deadline = SimpleDate.forward(date, 3 * 86400);

              options.user_trackId = tmp2.user_trackId;
              options.user_account = tmp2.user_account;
              options.user_password = tmp2.user_password;
              options.user_name = tmp2.user_name;
              options.user_email = tmp2.user_email;
              options.user_type = tmp2.user_type;
              
              options.events = tmp2.v2_events;
              result = this.generate(tmp, options);
              produces = produces.concat(result.p);
              for (var m = 0, ml = result.n.length; m < ml; m++) {
                n[n.length] = result.n[m];
              }
              for (var mm = 0, mml = result.e.length; mm < mml; mm++) {
                e[e.length] = result.e[mm];
              }
              for (var k = 0, kl = result.s.length; k < kl; k++) {
                ps[ps.length] = result.s[k];
              }
            }
            existed = true;
          }
        }
        //如果设计不存在
        if (!existed) {
          //先检查一下：刚刚（这次循环里）是不是已经加过了。
          var generated = false;
          for (var j = 0, jl = produces.length; j < jl; j++) {
            var tmp2 = produces[j];
            if (tmp2.pi_trackId == tmp.otherId) {
              //把相册放到设计中包含的相册去
              var purchaseItem = this.renew(tmp);
              var selects = this.renew(tmp.selects);
              var sels = [];
              for (var ii = 0, iil = selects.length; ii < iil; ii++) {
                var sel = selects[ii];
                sel.purchase_trackId = purchaseItem.trackId;
                s[s.length] = sel;
                sels[sels.length] = sel;
              }
              purchaseItem.produce_trackId = tmp2.trackId;
              purchaseItem.v2_selects = sels;
              pi[pi.length] = purchaseItem;
              tmp2.v2_purchaseItems[tmp2.v2_purchaseItems.length] = purchaseItem;
              generated = true;
            }
          }
          //如果没有加过，那么生成设计流程
          if (!generated) {
            options.state = 1;
            options.deadline = SimpleDate.forward(date, 14 * 86400);
            var purchase = v1purchaseitem.instance();
            purchase.notes = [];
            purchase.selects = [];
            purchase.trackId = tmp.otherId;
            purchase.quantity = 1;
            purchase.sampleId = tmp.sampleId;
            purchase.price = tmp.price;
            purchase.unit = tmp.unit;
            purchase.type = tmp.type;
            purchase.selects = tmp.selects;
            purchase.total = tmp.total;
            purchase.packageInc = tmp.packageInc;
            purchase.name = 'Album Design';
            purchase.model = Constant.MODEL_NAME_ALBUM_DESIGN;
            result = this.generate(purchase, options);
            for (var m = 0, ml = result.n.length; m < ml; m++) {
              n[n.length] = result.n[m];
            }
            for (var mm = 0, mml = result.e.length; mm < mml; mm++) {
              e[e.length] = result.e[mm];
            }
            for (var k = 0, kl = result.s.length; k < kl; k++) {
              ps[ps.length] = result.s[k];
            }
            //把相册放到设计中包含的相册去
            var purchaseItem = this.renew(tmp);
            var selects = this.renew(tmp.selects);
            var sels = [];
            for (var ii = 0, iil = selects.length; ii < iil; ii++) {
              var sel = selects[ii];
              sel.purchase_trackId = purchaseItem.trackId;
              s[s.length] = sel;
              sels[sels.length] = sel;
            }
            purchaseItem.produce_trackId = result.p.trackId;
            purchaseItem.v2_selects = sels;
            pi[pi.length] = purchaseItem;
            result.p.v2_purchaseItems = [];
            result.p.v2_purchaseItems[result.p.v2_purchaseItems.length] = purchaseItem;
            designs = designs.concat(result.p);
            produces = produces.concat(result.p);
          }
        }
      }
      //如果产品已经添加过了或者没有流程，那么就跳过。
      if (tmp._added || tmp.model == '') {
        continue;
      }
      //如果是工作人员产品，就直接添加
      if (tmp.model == Constant.MODEL_NAME_USER_PHOTOGRAPHER || tmp.model == Constant.MODEL_NAME_USER_VIDEOGRAPHER || tmp.model == Constant.MODEL_NAME_USER_MAKEUP || tmp.model == Constant.MODEL_NAME_USER_LIGHT ||  tmp.model == Constant.MODEL_NAME_PRODUCT_SLIDESHOWW) {
        result = this.generate(tmp, options);
        produces = produces.concat(result.p);
        for (var m = 0, ml = result.n.length; m < ml; m++) {
          n[n.length] = result.n[m];
        }
        for (var mm = 0, mml = result.e.length; mm < mml; mm++) {
          e[e.length] = result.e[mm];
        }
        for (var k = 0, kl = result.s.length; k < kl; k++) {
          ps[ps.length] = result.s[k];
        }
      }
      //处理相册设计（但是根本没有这个产品？）、精修照片、精修照片杂志、4x6照片、幻灯片、在线幻灯片：如果摄影师总数大于0，没完成摄影师数等于0（=摄影师都完成了）。不然就不管
      if ((total.length > 0 && completed.length == 0) && (tmp.model == Constant.MODEL_NAME_ALBUM_DESIGN || tmp.model == Constant.MODEL_NAME_PRODUCT_COMMON || tmp.model == Constant.MODEL_NAME_PRODUCT_RETOUCH || tmp.model == Constant.MODEL_NAME_PRODUCT_RETOUCH_MAGAZINE || tmp.model == Constant.MODEL_NAME_PRODUCT_4X6 || tmp.model == Constant.MODEL_NAME_PRODUCT_SLIDESHOW || tmp.model == Constant.MODEL_NAME_PRODUCT_SLIDESHOW_OL)) {
        //首先把相册、精修照片杂志去除
        if (tmp.type != Constant.SAMPLE_TYPE_ALBUM && tmp.type != Constant.SAMPLE_TYPE_MAGAZINE && tmp.model != Constant.MODEL_NAME_PRODUCT_RETOUCH_MAGAZINE) {
          options.state = 1;
          options.deadline = SimpleDate.forward(date, 14 * 86400);
          result = this.generate(tmp, options);
          produces = produces.concat(result.p);
          for (var m = 0, ml = result.n.length; m < ml; m++) {
            n[n.length] = result.n[m];
          }
          for (var mm = 0, mml = result.e.length; mm < mml; mm++) {
            e[e.length] = result.e[mm];
          }
          for (var k = 0, kl = result.s.length; k < kl; k++) {
            ps[ps.length] = result.s[k];
          }
        } else if (tmp.model == Constant.MODEL_NAME_PRODUCT_RETOUCH_MAGAZINE && rready) {
          //（如果没有精修照片就会报错？）
          MiscUtils.sort(retouch[0].v2_events, ['id']);
          options.events = retouch[0].v2_events;
          options.state = 12;
          options.deadline = SimpleDate.forward(date, 3 * 86400);
          options.user_trackId = retouch[0].user_trackId;
          options.user_account = retouch[0].user_account;
          options.user_password = retouch[0].user_password;
          options.user_name = retouch[0].user_name;
          options.user_email = retouch[0].user_email;
          options.user_type = retouch[0].user_type;
          result = this.generate(tmp, options);
          produces = produces.concat(result.p);
          for (var m = 0, ml = result.n.length; m < ml; m++) {
            n[n.length] = result.n[m];
          }
          for (var mm = 0, mml = result.e.length; mm < mml; mm++) {
            e[e.length] = result.e[mm];
          }
          for (var k = 0, kl = result.s.length; k < kl; k++) {
            ps[ps.length] = result.s[k];
          }
        }
      }
    } /* 如果是录像产品 */ else {
      //如果产品已经添加过了或者没有流程，那么就跳过。
      if (tmp._added || tmp.model == '') {
        continue;
      }
      //处理录像，Blu Ray录像剪辑：如果录像师都已经完成了
      if ((vtotal.length > 0 && vcompleted.length == 0 && vmusic.length == 1 && vrequirement.length == 1) && ((tmp.model == Constant.MODEL_NAME_PRODUCT_VIDEO) || (tmp.model == Constant.MODEL_NAME_PRODUCT_VIDEO_BLURAY))) {
        options.state = 1;
        options.deadline = SimpleDate.forward(date, 28 * 86400);
        result = this.generate(tmp, options);
        produces = produces.concat(result.p);
        for (var m = 0, ml = result.n.length; m < ml; m++) {
          n[n.length] = result.n[m];
        }
        for (var mm = 0, mml = result.e.length; mm < mml; mm++) {
          e[e.length] = result.e[mm];
        }
        for (var k = 0, kl = result.s.length; k < kl; k++) {
          ps[ps.length] = result.s[k];
        }
      } /* 如果是录像DVD产品，并且录像剪辑已完成 */ else if ((vedit.length >= 1) && (tmp.model == Constant.MODEL_NAME_PRODUCT_VIDEODVD)) {
        options.state = 1;
        options.deadline = SimpleDate.forward(date, 5 * 86400);
        result = this.generate(tmp, options);
        produces = produces.concat(result.p);
        for (var m = 0, ml = result.n.length; m < ml; m++) {
          n[n.length] = result.n[m];
        }
        for (var mm = 0, mml = result.e.length; mm < mml; mm++) {
          e[e.length] = result.e[mm];
        }
        for (var k = 0, kl = result.s.length; k < kl; k++) {
          ps[ps.length] = result.s[k];
        }
      } /* 如果是Blu Ray录像DVD产品，并且Blu Ray录像剪辑已完成 */ else if ((veditbr.length >= 1) && (tmp.model == Constant.MODEL_NAME_PRODUCT_VIDEODVD_BLURAY)) {
        options.state = 1;
        options.deadline = SimpleDate.forward(date, 5 * 86400);
        result = this.generate(tmp, options);
        produces = produces.concat(result.p);
        for (var m = 0, ml = result.n.length; m < ml; m++) {
          n[n.length] = result.n[m];
        }
        for (var mm = 0, mml = result.e.length; mm < mml; mm++) {
          e[e.length] = result.e[mm];
        }
        for (var k = 0, kl = result.s.length; k < kl; k++) {
          ps[ps.length] = result.s[k];
        }
      }
    }
  }
  
  //以下的代码，主要负责更新。
  //处理动作包括：添加/更新 ProducePurchaseItem, ProducePurchaseItemSelect, ProduceSelect，更新 v2_purchaseItem, pi_select
  //###如果是修改问题，就要检查以下的代码###
  //produces里面加过新产品，因此要更新avlPurchases, avlProduces
  avlPurchases = MiscUtils.find(purchases, [{ attrs: ['cancelled'], value: 0 }]);
  avlProduces = MiscUtils.find(produces, [{ attrs: ['cancelled'], value: 0 }, { attrs: ['_deleted'], value: undefined }, { attrs: ['orderTrackId'], value: orderTrackId }]);
  this.compare(avlPurchases, avlProduces);
  
  //主要是两个循环：1产品，2流程，逐个比较。
  for (var i = 0, il = avlPurchases.length; i < il; i++) {
    tmp = avlPurchases[i];
    for (var j = 0, jl = avlProduces.length; j < jl; j++) {
      tmp2 = avlProduces[j];
      //流程分为2类：1设计（更新它包含的相册和相册属性），2其它产品（更新属性）
      if (tmp2.pi_model == Constant.MODEL_NAME_ALBUM_DESIGN) {
        tmp2.pi_quantity = 1;
        //更新设计中包含的相册和相册属性。更新pi, s（ProducePurchaseItem，ProducePurchaseItemSelect）
        //用设计中的每个ProducePurchaseItem和Purchase比较
        for (var k = 0, kl = tmp2.v2_purchaseItems.length; k < kl; k++) {
          var tmp3 = tmp2.v2_purchaseItems[k];
          if (tmp3.trackId == tmp.trackId) {
            //ProducePurchaseItem是否已经存在:
            //如果没有，就添加。否则，就更新
            //###避免重复更新###
            var tmpPI = MiscUtils.find(pi, [{ attrs: ['trackId'], value: tmp3.trackId }]);
            if (tmpPI.length == 0) {
              tmp3.quantity = tmp.quantity;
              pi[pi.length] = tmp3;
            } else {
              tmp3.quantity = tmp.quantity;
              tmpPI[0].quantity = tmp.quantity;
            }
            //如果设计中的ProducePurchaseItem和Purchase是同一个产品（相册），然后开始比较它们的属性
            for (var l = 0, ll = tmp3.v2_selects.length; l < ll; l++) {
              tmp4 = tmp3.v2_selects[l];
              for (var m = 0, ml = tmp.selects.length; m < ml; m++) {
                tmp5 = tmp.selects[m];
                if (tmp4.title == tmp5.title) {
                  //ProducePurchaseItemSelect是否已经存在:
                  //如果没有，就添加。否则，就更新
                  //###避免重复更新###
                  var tmpPIS = MiscUtils.find(s, [{ attrs: ['trackId'], value: tmp4.trackId }]);
                  if (tmpPIS.length == 0) {
                    tmp4.sampleAttributeOptionId = tmp5.sampleAttributeOptionId;
                    tmp4.value = tmp5.value;
                    s[s.length] = tmp4;
                  } else {
                    tmp4.sampleAttributeOptionId = tmp5.sampleAttributeOptionId;
                    tmp4.value = tmp5.value;
                    tmpPIS[0].sampleAttributeOptionId = tmp5.sampleAttributeOptionId;
                    tmpPIS[0].value = tmp5.value;
                  }
                }
              }
            }
          }
        }
      } else {
        if (tmp2.pi_trackId == tmp.trackId) {
          tmp2.pi_quantity = tmp.quantity;
          //更新产品属性。更新ps（ProduceSelect）
          if (!tmp2.pi_selects) {
            tmp2.pi_selects = [];
          }
          for (var k = 0, kl = tmp2.pi_selects.length; k < kl; k++) {
            tmp3 = tmp2.pi_selects[k];
            for (var l = 0, ll = tmp.selects.length; l < ll; l++) {
              tmp4 = tmp.selects[l];
              if (tmp3.title == tmp4.title) {
                //ProduceSelect是否已经存在:
                //如果没有，就添加。否则，就更新
                //###避免重复更新###
                var tmpPS = MiscUtils.find(ps, [{ attrs: ['trackId'], value: tmp3.trackId }]);
                if (tmpPS.length == 0) {
                  tmp3.value = tmp4.value;
                  ps[ps.length] = tmp3;
                } else {
                  tmp3.value = tmp4.value;
                  tmpPS[0].value = tmp4.value;
                }
              }
            }
          }
          //如果是工作人员流程还要更新工作时间（estimates）
          if (tmp2.pi_model == Constant.MODEL_NAME_USER_PHOTOGRAPHER || tmp2.pi_model == Constant.MODEL_NAME_USER_VIDEOGRAPHER || tmp2.pi_model == Constant.MODEL_NAME_USER_MAKEUP || tmp2.pi_model == Constant.MODEL_NAME_USER_LIGHT) {
            tmp2.estimates = tmp.quantity;
          }
        }
      }
    }
  }
  //更新完设计中包含的相册和相册属性，然后更新设计的属性
  for (var j = 0, jl = avlProduces.length; j < jl; j++) {
    tmp2 = avlProduces[j];
    //更新设计的属性
    if (tmp2.pi_model == Constant.MODEL_NAME_ALBUM_DESIGN) {
      //更新设计的属性
      //更新ps（ProduceSelect）
      if (!tmp2.pi_selects) {
        tmp2.pi_selects = [];
      }
      //主要是三个循环：1设计属性，2设计中的相册，3相册属性。
      for (var k = 0, kl = tmp2.pi_selects.length; k < kl; k++) {
        tmp3 = tmp2.pi_selects[k];
        if (tmp3.title == 'Pages') {
          tmp3.value = 0;
        }
        for (var l = 0, ll = tmp2.v2_purchaseItems.length; l < ll; l++) {
          var tmp4 = tmp2.v2_purchaseItems[l];
          //原来以为produceread.php读取的时候，设计中的相册（ProducePurchaseItem）没有属性（ProducePurchaseItemSelect），因此要去产品（Purchase）里面找出对应的对象
          //但是现在有的，所以这一步好像多余的。
          var tmpPurchases = MiscUtils.find(avlPurchases, [{ attrs: ['trackId'], value: tmp4.trackId }]);
          if (tmpPurchases.length == 1) {
            tmp = tmpPurchases[0];
            for (var m = 0, ml = tmp.selects.length; m < ml; m++) {
              var tmp5 = tmp.selects[m];
              if (tmp3.title == tmp5.title && tmp3.title != 'Pages') {
                //ProduceSelect是否已经存在:
                //如果没有，就添加。否则，就更新
                //###避免重复更新###
                var tmpPS = MiscUtils.find(ps, [{ attrs: ['trackId'], value: tmp3.trackId }]);
                if (tmpPS.length == 0) {
                  tmp3.value = tmp5.value;
                  ps[ps.length] = tmp3;
                } else {
                  tmp3.value = tmp5.value;
                  tmpPS[0].value = tmp5.value;
                }
              } else if (tmp3.title == tmp5.title && tmp3.title == 'Pages') {
                //ProduceSelect是否已经存在:
                //如果没有，就添加。否则，就更新
                //###避免重复更新###
                var tmpPS = MiscUtils.find(ps, [{ attrs: ['trackId'], value: tmp3.trackId }]);
                if (tmpPS.length == 0) {
                  tmp3.value = Math.max(tmp5.value, tmp3.value);
                  ps[ps.length] = tmp3;
                } else {
                  tmp3.value = Math.max(tmp5.value, tmp3.value);
                  tmpPS[0].value = Math.max(tmp5.value, tmpPS[0].value);
                }
              }
            }
          }
        }
      }
    }
  }
  //*********************************更新代码到此结束***********************************************

  /* Additional actions */
  avlPurchases = MiscUtils.find(purchases, [{ attrs: ['cancelled'], value: 0 }]);
  avlProduces = MiscUtils.find(produces, [{ attrs: ['cancelled'], value: 0 }, { attrs: ['_deleted'], value: undefined }, { attrs: ['orderTrackId'], value: orderTrackId }]);

  result = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_PHOTOGRAPHER }, { attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_VIDEOGRAPHER }, { attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_MAKEUP }, { attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_LIGHT }, { attrs: ['pi_model'], value: Constant.MODEL_NAME_ALBUM_DESIGN }], MiscUtils.disjunction);
  if (!options._modified) {
    this.rename(result);
  }

  result = MiscUtils.find(avlProduces, [{ attrs: ['pi_model'], value: Constant.MODEL_NAME_PRODUCT_SLIDESHOWW },{ attrs: ['pi_model'], value: Constant.MODEL_NAME_PRECON }, { attrs: ['pi_model'], value: Constant.MODEL_NAME_MUSIC }, { attrs: ['pi_model'], value: Constant.MODEL_NAME_REQUIREMENT }, { attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_PHOTOGRAPHER }, { attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_VIDEOGRAPHER }, { attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_MAKEUP }, { attrs: ['pi_model'], value: Constant.MODEL_NAME_USER_LIGHT }], MiscUtils.disjunction);
  
  if (orderDate) {
    for (var i = 0, il = result.length; i < il; i++) {
      tmp = result[i];
      tmp.date = orderDate;
      if (tmp.pi_model == Constant.MODEL_NAME_PRECON && (tmp.state == 1 || tmp.state == 0)) {
        tmp.state = 1;
        tmp.deadline = SimpleDate.backward(orderDate, 21 * 86400);
      } else if (tmp.pi_model == Constant.MODEL_NAME_MUSIC && (tmp.state == 1 || tmp.state == 0)) {
        tmp.state = 1;
        tmp.deadline = SimpleDate.backward(orderDate, 21 * 86400);
      } else if (tmp.pi_model == Constant.MODEL_NAME_REQUIREMENT && (tmp.state == 1 || tmp.state == 0)) {
        tmp.state = 1;
        tmp.deadline = SimpleDate.backward(orderDate, 21 * 86400);
      } else if (tmp.pi_model == Constant.MODEL_NAME_USER_PHOTOGRAPHER && (tmp.state == 1 || tmp.state == 0)) {
        tmp.state = 1;
        tmp.deadline = SimpleDate.backward(orderDate, 90 * 86400);
      } else if (tmp.pi_model == Constant.MODEL_NAME_USER_VIDEOGRAPHER && (tmp.state == 1 || tmp.state == 0)) {
        tmp.state = 1;
        tmp.deadline = SimpleDate.backward(orderDate, 90 * 86400);
      } else if (tmp.pi_model == Constant.MODEL_NAME_USER_MAKEUP && (tmp.state == 1 || tmp.state == 0)) {
        tmp.state = 1;
        tmp.deadline = SimpleDate.backward(orderDate, 90 * 86400);
      } else if (tmp.pi_model == Constant.MODEL_NAME_USER_LIGHT && (tmp.state == 1 || tmp.state == 0)) {
        tmp.state = 1;
        tmp.deadline = SimpleDate.backward(orderDate, 90 * 86400);
      }
	  
      
      if(tmp.pi_model == Constant.MODEL_NAME_PRODUCT_SLIDESHOWW && (tmp.state == 1 || tmp.state == 0) ){
        tmp.state = 1;
        tmp.deadline = SimpleDate.backward(orderDate, 0);
      }	  
	  
      if (tmp.pi_model == Constant.MODEL_NAME_USER_PHOTOGRAPHER && (tmp.state == 2)) {
        tmp.deadline = SimpleDate.backward(orderDate, 30 * 86400);
      }
      if (tmp.pi_model == Constant.MODEL_NAME_USER_PHOTOGRAPHER && (tmp.state == 3)) {
        tmp.deadline = SimpleDate.backward(orderDate, 2 * 86400);
      }
      if (tmp.pi_model == Constant.MODEL_NAME_USER_PHOTOGRAPHER && (tmp.state == 4)) {
        tmp.deadline = SimpleDate.forward(orderDate, 4 * 86400);
      }
      if (tmp.pi_model == Constant.MODEL_NAME_USER_VIDEOGRAPHER && (tmp.state == 2)) {
        tmp.deadline = SimpleDate.backward(orderDate, 30 * 86400);
      }
      if (tmp.pi_model == Constant.MODEL_NAME_USER_VIDEOGRAPHER && (tmp.state == 3)) {
        tmp.deadline = SimpleDate.backward(orderDate, 2 * 86400);
      }
      if (tmp.pi_model == Constant.MODEL_NAME_USER_VIDEOGRAPHER && (tmp.state == 4)) {
        tmp.deadline = SimpleDate.forward(orderDate, 4 * 86400);
      }
      if (tmp.pi_model == Constant.MODEL_NAME_USER_MAKEUP && (tmp.state == 2)) {
        tmp.deadline = SimpleDate.backward(orderDate, 30 * 86400);
      }
      if (tmp.pi_model == Constant.MODEL_NAME_USER_MAKEUP && (tmp.state == 3)) {
        tmp.deadline = SimpleDate.backward(orderDate, 2 * 86400);
      }
      if (tmp.pi_model == Constant.MODEL_NAME_USER_LIGHT && (tmp.state == 2)) {
        tmp.deadline = SimpleDate.backward(orderDate, 30 * 86400);
      }
      if (tmp.pi_model == Constant.MODEL_NAME_USER_LIGHT && (tmp.state == 3)) {
        tmp.deadline = SimpleDate.backward(orderDate, 2 * 86400);
      }
    }
  } else {
    for (var i = 0, il = avlProduces.length; i < il; i++) {
      var tmp = avlProduces[i];
      tmp.date = null;
      tmp.state = 0;
      tmp.deadline = null;
    }
  }
  
  return { produces: produces,
           produceSelects: ps,
           events: e,
           notes: n,
           purchaseItems: pi,
           purchaseItemSelects: s
         };
};

/**
 *synchronise end
 */

/**
 * 计算产品和流程的差值（摄影师、摄像师）
 */
DlmanageUtils.balance = function(purchases, produces) {
  var array, total = 0, used = 0, photo = 0, video = 0, travel = 0,light = 0,makeup = 0;

  purchases = MiscUtils.find(purchases, [{ attrs: ['cancelled'], value: 0 }])
  produces = MiscUtils.find(produces, [{ attrs: ['_deleted'], value: undefined }, { attrs: ['cancelled'], value: 0 }])
  
  array = MiscUtils.find(purchases, [{ attrs: ['type'], value: '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_PHOTOGRAPHER_WITH_HOURS)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' }, { attrs: ['type'], value: '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_PHOTO_HOUR)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' }], MiscUtils.disjunction)
  for (var i = 0, il = array.length; i < il; i++) {
    var tmp = array[i];
    total += parseFloat(tmp.quantity, 10);
  }
  array = MiscUtils.find(produces, [{ attrs: ['pi_model'], value: '<?php echo ((is_array($_tmp=@MODEL_NAME_USER_PHOTOGRAPHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' }], MiscUtils.disjunction)
  for (var i = 0, il = array.length; i < il; i++) {
    var tmp = array[i];
    used += parseFloat(tmp.estimates, 10) + parseFloat(tmp.extras, 10);
    travel += parseFloat(tmp.travels, 10);
  }
  photo = total - used;
  
  array = MiscUtils.find(purchases, [{ attrs: ['type'], value: '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_VIDEOGRAPHER_WITH_HOURS)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' }, { attrs: ['type'], value: '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_VIDEO_HOUR)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' }], MiscUtils.disjunction)
  total = 0, used = 0;
  for (var i = 0, il = array.length; i < il; i++) {
    var tmp = array[i];
    total += parseFloat(tmp.quantity, 10);
  }
  array = MiscUtils.find(produces, [{ attrs: ['pi_model'], value: '<?php echo ((is_array($_tmp=@MODEL_NAME_USER_VIDEOGRAPHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' }], MiscUtils.disjunction)
  for (var i = 0, il = array.length; i < il; i++) {
    var tmp = array[i];
    used += parseFloat(tmp.estimates, 10) + parseFloat(tmp.extras, 10);
    travel += parseFloat(tmp.travels, 10);
  }
  video = total - used;
  
  array = MiscUtils.find(purchases, [{ attrs: ['type'], value: '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_TRAVEL)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' }], MiscUtils.disjunction)
  total = 0, used = 0;
  for (var i = 0, il = array.length; i < il; i++) {
    var tmp = array[i];
    total += parseFloat(tmp.price * tmp.quantity, 10);
  }
  travel = total - travel;
  
  return { photo: photo,
           video: video,
           travel: travel
         };
};

/**
 * 把任务转换成模式和状态的数据库询问语句
 */
DlmanageUtils.lookup = function(text, models) {
  var sql = '';
  for (var i = 0, il = models.length; i < il; i++) {
    var model = models[i];
    for (var j = 0, jl = model.states.length; j < jl; j++) {
      var state = model.states[j];
      if (state.title.indexOf(text) != -1) {
        sql += ((sql == '') ? '(' : ' OR ') + '(d.pi_model =\'' + model.name + '\' AND d.state = \'' + state.id + '\' AND d.cancelled = 0)';
      }
    }
  }
  sql += ((sql == '') ? '1 != 1' : ')');
  return sql;
};

/**
 * 把对象数组转换成它们id数组
 */
DlmanageUtils.identifiers = function(objects) {
  var array = [];
  for (var i = 0, il = objects.length; i < il; i++) {
    var tmp = objects[i];
    array[array.length] = tmp.id;
  }
  return array;
};

/**
 * 把数组转换成sql询问语句
 */
DlmanageUtils.enquiry = function(identifiers) {
  var sql = '';
  for (var i = 0, il = identifiers.length; i < il; i++) {
    var tmp = identifiers[i];
    sql += ((sql == '') ? '' : ' OR ') + 'd.e_oid = \'' + tmp + '\'';
  }
  return sql;
};

/**
 * 更新邮寄中产品的状态
 */
DlmanageUtils.send = function(produce, produces, models, user, date) {
  var pros = []; events = []; tracks = [];
  for (var i = 0, il = produces.length; i < il; i++) {
    var tmp = produces[i];
    tmp.parent_trackId = produce.trackId;
    
    var model = models[tmp.pi_model];
    var transitions = [];
    for (var j = 0, jl = model.states.length; j < jl; j++) {
      var s = model.states[j];
      if (tmp.state == s.id) {
        state = s;
        break;
      }
    }
    
    for (var j = 0, jl = model.transitions.length; j < jl; j++) {
      var t = model.transitions[j];
      if (tmp.state == t.source.id) {
        transitions[transitions.length] = t;
      }
    }
    
    if (transitions.length > 0 && ((tmp.pi_model == Constant.MODEL_NAME_PRODUCT_COMMON && tmp.state == 15) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_RETOUCH_MAGAZINE && tmp.state == 15) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_4X6 && tmp.state == 9) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_SLIDESHOW && tmp.state == 7) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_SLIDESHOW_OL && tmp.state == 7) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_VIDEODVD && tmp.state == 4) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_VIDEODVD_BLURAY && tmp.state == 4))) {
      tracks[tracks.length] = this.getTrack(tmp, user, date, transitions[0], '');
      events[events.length] = this.record(tmp, user, date, transitions[0], null, null);
      this.transit(transitions[0], tmp, date);
      pros[pros.length] = tmp;
    }
  }
  return { p: pros,
           e: events,
           t: tracks
         };
};

/**
 * 更新邮寄中产品的状态
 */
DlmanageUtils.sendTapes = function(produce, produces, models, user, date) {
  var pros = []; events = []; tracks = [];
  for (var i = 0, il = produces.length; i < il; i++) {
    var tmp = produces[i];
    tmp.parent_trackId = produce.trackId;
    
    var model = models[tmp.pi_model];
    var transitions = [];
    for (var j = 0, jl = model.states.length; j < jl; j++) {
      var s = model.states[j];
      if (tmp.state == s.id) {
        state = s;
        break;
      }
    }
    
    for (var j = 0, jl = model.transitions.length; j < jl; j++) {
      var t = model.transitions[j];
      if (tmp.state == t.source.id) {
        transitions[transitions.length] = t;
      }
    }
    
    if (transitions.length > 0 && (( (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_VIDEO || tmp.pi_model == Constant.MODEL_NAME_PRODUCT_VIDEO_BLURAY ) && tmp.state == 2))) {
      tracks[tracks.length] = this.getTrack(tmp, user, date, transitions[0], '');
      events[events.length] = this.record(tmp, user, date, transitions[0], null, null);
      this.transit(transitions[0], tmp, date);
      pros[pros.length] = tmp;
    }
  }
  return { p: pros,
           e: events,
           t: tracks
         };
};

/**
 * 更新邮寄中产品的状态
 */
DlmanageUtils.receive = function(produces, models, user, date, options) {
  var pros = []; events = []; tracks = [];
  for (var i = 0, il = produces.length; i < il; i++) {
    var tmp = produces[i];
    
//    MiscUtils.sort(tmp.tracks, ['id']);
    
    var model = models[tmp.pi_model];
    var transitions = [];
    for (var j = 0, jl = model.states.length; j < jl; j++) {
      var s = model.states[j];
      if (tmp.state == s.id) {
        state = s;
        break;
      }
    }
    
    for (var j = 0, jl = model.transitions.length; j < jl; j++) {
      var t = model.transitions[j];
      if (tmp.state == t.source.id) {
        transitions[transitions.length] = t;
      }
    }
    
    if (transitions.length > 0 && ((tmp.pi_model == Constant.MODEL_NAME_PRODUCT_COMMON && tmp.state == 16) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_RETOUCH_MAGAZINE && tmp.state == 16) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_4X6 && tmp.state == 10) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_SLIDESHOW && tmp.state == 8) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_SLIDESHOW_OL && tmp.state == 8) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_VIDEODVD && tmp.state == 5) || 
        (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_VIDEODVD_BLURAY && tmp.state == 5))) {
      if (tmp._received) {
        tracks[tracks.length] = this.getTrack(tmp, user, date, transitions[0], '');
        events[events.length] = this.record(tmp, user, date, transitions[0], null, null);
        this.transit(transitions[0], tmp, date);
        pros[pros.length] = tmp;
      } else {
        tracks[tracks.length] = this.getTrack(tmp, user, date, null, ((options && options.extra) ? 'LOST: ' + options.extra : ''));
        var e = ProduceEvent.instance();
        e.produce_trackId = tmp.trackId;
        e.date = date;
        e.userAccount = user.account;
        e.extra = 'LOST: ' + ((options && options.extra) ? options.extra : '');
        events[events.length] = e;
        tmp.state--;
        pros[pros.length] = tmp;
      }
    }
  }
  return { p: pros,
           e: events,
           t: tracks
         };
};

/**
 * 更新邮寄中产品的状态
 */
DlmanageUtils.receiveTapes = function(produces, models, user, date, options) {
  var pros = []; events = []; tracks = [];
  for (var i = 0, il = produces.length; i < il; i++) {
    var tmp = produces[i];
    
//    MiscUtils.sort(tmp.tracks, ['id']);
    
    var model = models[tmp.pi_model];
    var transitions = [];
    for (var j = 0, jl = model.states.length; j < jl; j++) {
      var s = model.states[j];
      if (tmp.state == s.id) {
        state = s;
        break;
      }
    }
    
    for (var j = 0, jl = model.transitions.length; j < jl; j++) {
      var t = model.transitions[j];
      if (tmp.state == t.source.id) {
        transitions[transitions.length] = t;
      }
    }
    
    if (transitions.length > 0 && (( (tmp.pi_model == Constant.MODEL_NAME_PRODUCT_VIDEO || tmp.pi_model == Constant.MODEL_NAME_PRODUCT_VIDEO_BLURAY ) && tmp.state == 3))) {
      if (tmp._received) {
        tracks[tracks.length] = this.getTrack(tmp, user, date, transitions[0], '');
        events[events.length] = this.record(tmp, user, date, transitions[0], null, null);
        this.transit(transitions[0], tmp, date);
        pros[pros.length] = tmp;
      } else {
        tracks[tracks.length] = this.getTrack(tmp, user, date, null, ((options && options.extra) ? 'LOST: ' + options.extra : ''));
        var e = ProduceEvent.instance();
        e.produce_trackId = tmp.trackId;
        e.date = date;
        e.userAccount = user.account;
        e.extra = 'LOST: ' + ((options && options.extra) ? options.extra : '');
        events[events.length] = e;
        tmp.state--;
        pros[pros.length] = tmp;
      }
    }
  }
  return { p: pros,
           e: events,
           t: tracks
         };
};

/**
 * 
 */
DlmanageUtils.change = function(popupBox, pos, callbackFunc, produce, user, date, options) {
  var div = document.createElement('div');
  var tmp = produce.user_account;
  
  var track = this.getTrack(produce, user, date, null, '');
  
  var func1 = function() { popupBox._close();
                           if (track) {
                             if (track.user_trackId == produce.user_trackId) {
                               callbackFunc();
                               return;
                             }
                           }
                           var e = ProduceEvent.instance();
                           e.produce_trackId = produce.trackId;
                           e.date = date;
                           e.userAccount = user.account;
                           e.extra = 'ALTER TO ' + produce.user_account + ' (' + tmp + ')';
                           
                           track.extra = 'ALTER TO ' + produce.user_account + ' (' + tmp + ')';
                           
                           if (produce.pi_model == Constant.MODEL_NAME_ALBUM_DESIGN || produce.pi_model == Constant.MODEL_NAME_PRODUCT_4X6 || produce.pi_model == Constant.MODEL_NAME_PRODUCT_RETOUCH || produce.pi_model == Constant.MODEL_NAME_PRODUCT_COMMON) {
                             produce.state = (produce.state > 3) ? 3 : produce.state;
                             produce.modified = 0;
                           }
                           new RequestUtils()._write2([{ n: 'produce', a: [produce], r: [] }, { n: 'produceevent', a: [e], r: [] }, { n: 'producetrack', a: [track], r: [] }], callbackFunc, { php: Constant.FACTORY + '/customphp/mysqlwrite2.php', pos: pos });
                         };
  var func2 = function() { popupBox._close();
                           callbackFunc();
                         };
  var condition = 'd.type = \'<?php echo ((is_array($_tmp=@USER_TYPE_DESIGNER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\'';
  if (produce.pi_model == Constant.MODEL_NAME_USER_PHOTOGRAPHER) {
    condition = 'd.pEnabled = 1 and d.isdisplay = 0';
  } else if (produce.pi_model == Constant.MODEL_NAME_USER_VIDEOGRAPHER) {
    condition = 'd.vEnabled = 1 and d.isdisplay = 0';
  } else if (produce.pi_model == Constant.MODEL_NAME_USER_MAKEUP) {
    condition = 'd.mEnabled = 1 and d.isdisplay = 0';
  } else if (produce.pi_model == Constant.MODEL_NAME_USER_LIGHT) {
    condition = '1 = 1 and d.isdisplay = 0';
  }
  MiscUtils.dialog(popupBox, pos, div, func1, func2);
  if (options && options.func) {
    options.func(div, produce, condition);
  }
};

/**
 * 返回每种订单的支付方式
 */
DlmanageUtils.payment = function(type) {
  if (type == Constant.ORDER_TYPE_WEDDING) {
    return [ { rate: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_RATE1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_PERC1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_TITLE1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_COMMENT1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'},
             { rate: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_RATE2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_PERC2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_TITLE2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_COMMENT2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'},
             { rate: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_RATE3)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_PERC3)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_TITLE3)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_COMMENT3)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'},
             { rate: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_RATE4)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_PERC4)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_TITLE4)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@WEDDING_PAYMENT_COMMENT4)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'}
           ];
  } else if (type == Constant.ORDER_TYPE_PREWEDDING) {
    return [ { rate: '<?php echo ((is_array($_tmp=@PREWEDDING_PAYMENT_RATE1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@PREWEDDING_PAYMENT_PERC1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@PREWEDDING_PAYMENT_TITLE1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@PREWEDDING_PAYMENT_COMMENT1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'},
             { rate: '<?php echo ((is_array($_tmp=@PREWEDDING_PAYMENT_RATE2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@PREWEDDING_PAYMENT_PERC2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@PREWEDDING_PAYMENT_TITLE2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@PREWEDDING_PAYMENT_COMMENT2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'}
           ];
  } else if (type == Constant.ORDER_TYPE_PORTRAIT) {
    return [ { rate: '<?php echo ((is_array($_tmp=@PORTRAIT_PAYMENT_RATE1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@PORTRAIT_PAYMENT_PERC1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@PORTRAIT_PAYMENT_TITLE1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@PORTRAIT_PAYMENT_COMMENT1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'},
             { rate: '<?php echo ((is_array($_tmp=@PORTRAIT_PAYMENT_RATE2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@PORTRAIT_PAYMENT_PERC2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@PORTRAIT_PAYMENT_TITLE2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@PORTRAIT_PAYMENT_COMMENT2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'}
           ];
  } else if (type == Constant.ORDER_TYPE_ENGAGEMENT) {
    return [ { rate: '<?php echo ((is_array($_tmp=@ENGAGEMENT_PAYMENT_RATE1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@ENGAGEMENT_PAYMENT_PERC1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@ENGAGEMENT_PAYMENT_TITLE1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@ENGAGEMENT_PAYMENT_COMMENT1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'},
             { rate: '<?php echo ((is_array($_tmp=@ENGAGEMENT_PAYMENT_RATE2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@ENGAGEMENT_PAYMENT_PERC2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@ENGAGEMENT_PAYMENT_TITLE2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@ENGAGEMENT_PAYMENT_COMMENT2)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'}
           ];
  } else if (type == Constant.ORDER_TYPE_OTHER) {
    return [{ rate: '<?php echo ((is_array($_tmp=@OTHER_PAYMENT_RATE1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', perc: '<?php echo ((is_array($_tmp=@OTHER_PAYMENT_PERC1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', title: '<?php echo ((is_array($_tmp=@OTHER_PAYMENT_TITLE1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
', comment: '<?php echo ((is_array($_tmp=@OTHER_PAYMENT_COMMENT1)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'}];
  }
};

/**
 * 
 */
DlmanageUtils.customerId = function(customerId) {
  if (customerId < 100000 && customerId >= 10000) {
    customerId = customerId;
  } else if (customerId < 10000 && customerId >= 1000) {
    customerId = '0' + customerId;
  } else if (customerId < 1000 && customerId >= 100) {
    customerId = '00' + customerId;
  } if (customerId < 100 && customerId >= 10) {
    customerId = '000' + customerId;
  } if (customerId < 10 && customerId > 0) {
    customerId = '0000' + customerId;
  }
  return customerId;
};

/**
 * 计算折扣
 */

DlmanageUtils.total = function(order) {
  var total = 0, pho = order.photoprice, vdo = order.videoprice;
  for (var i = 0, il = order.purchaseItems.length; i < il; i++) {
    var tmp = order.purchaseItems[i];
    if (tmp.cancelled == 1 && tmp.packageInc == Constant.PACKAGE_TYPE_PHOTO) {
      if (order.photooriginal == 0) {
        var disc = 1;
      } else {
        var disc = Math.abs(1 - ((order.photooriginal - order.photoprice) / order.photooriginal));
      }
      pho -= parseFloat(tmp.total * disc, 10);
    } else if (tmp.cancelled == 1 && tmp.packageInc == Constant.PACKAGE_TYPE_VIDEO) {
      if (order.videooriginal == 0) {
        var disc = 1;
      } else {
        var disc = Math.abs(1 - ((order.videooriginal - order.videoprice) / order.videooriginal));
      }
      vdo -= parseFloat(tmp.total * disc, 10);
    } else if (tmp.cancelled == 0 && tmp.packageInc == '') {
      total += parseFloat(tmp.price * tmp.quantity, 10);
    }
  }
  var count = 0;
  for (var j = 0, jl = order.purchaseItems.length; j < jl; j++) {
    var tmp = order.purchaseItems[j];
    if (tmp.cancelled == 0) {
      if (tmp.isFree == 1 && (tmp.type == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_ALBUM)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' || tmp.type == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_MAGAZINE)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
')) {
        count++;
      }
    }
  }
  return (parseFloat(total, 10) + parseFloat((pho < 0) ? 0 : pho, 10) + parseFloat((vdo < 0) ? 0 : vdo, 10) + parseFloat(count * 180.00, 10)).toFixed(2);
};

/**
 * 
 */
DlmanageUtils.flag = function(customer, orderType) {
  var count = 0;
  for (var i = 0, il = customer.orders.length; i < il; i++) {
    var order = customer.orders[i];
    if (orderType == order.type) {
      var flag = order.flag.replace(Constant.ORDER_TYPE_WEDDING, '');
      flag = flag.replace(Constant.ORDER_TYPE_PREWEDDING, '');
      flag = flag.replace(Constant.ORDER_TYPE_PORTRAIT, '');
      flag = flag.replace(Constant.ORDER_TYPE_ENGAGEMENT, '');
      flag = flag.replace(Constant.ORDER_TYPE_OTHER, '');
      flag = (flag == '') ? 0 : flag;
      count++;
      count = Math.max(parseInt(flag, 10), count);
    }
  }
  return orderType + ((count == 0) ? '' :  (count + 1));
};

/**
 * 
 */
DlmanageUtils.query = function() {
  var query =  [ { id: 1, string: '(o.type=\'<?php echo ((is_array($_tmp=@ORDER_TYPE_WEDDING)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\')' },
                 { id: 2, string: '(o.type=\'<?php echo ((is_array($_tmp=@ORDER_TYPE_PREWEDDING)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\')' },
                 { id: 3, string: '(o.type=\'<?php echo ((is_array($_tmp=@ORDER_TYPE_PORTRAIT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\')' },
                 { id: 4, string: '(o.type=\'<?php echo ((is_array($_tmp=@ORDER_TYPE_ENGAGEMENT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\')' },
                 { id: 5, string: '(o.type=\'<?php echo ((is_array($_tmp=@ORDER_TYPE_OTHER)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
\')' }
               ];
  return query;
};

/**
 * 
 */
DlmanageUtils.search = function() {
  return { id: '',
           name: '',
           phone: '',
           weddingDay: null,
           dateFrom: null,
           dateTo: null,
           orderWedding: true,
           orderPrewedding: true,
           orderPortrait: true,
           orderEngagement: true,
           orderOther: true,
           orderfinished: false,
           datepFrom: null,
           datepTo: null           
         };
};

DlmanageUtils.acctExpenseSearch = function() {
  return { cdateFrom: null,
           cdateTo: null,
           pdateFrom: null,
           pdateTo: null,
           payee: '',
           particular: '',
           amount: '',
           method: '',
           chequeNo: '',
           note: '',
           ng: false,
           ne: false,
           paid: false,
           unpaid: false
         };
};

DlmanageUtils.acctPaymentSearch = function() {
  return { cdateFrom: null,
           cdateTo: null,
           pdateFrom: null,
           pdateTo: null,
           payer: '',
           item: '',
           sort: '',
           amount: '',
           method: '',
           verified: false,
           unverified: false
         };
};

DlmanageUtils.purchase = function(order) {
  var pPurchase = [], vPurchase = [], additions = [];
  for (var i = 0, il = order.purchaseItems.length; i < il; i++) {
    var purchase = order.purchaseItems[i];
    if (purchase.packageInc == '<?php echo ((is_array($_tmp=@PACKAGE_TYPE_PHOTO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      pPurchase[pPurchase.length] = purchase;
      
    } else if (purchase.packageInc == '<?php echo ((is_array($_tmp=@PACKAGE_TYPE_VIDEO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
      vPurchase[vPurchase.length] = purchase;
    } else {
      additions[additions.length] = purchase;
    }
  }
  return [pPurchase, vPurchase, additions];
};

DlmanageUtils.weekly = function(number) {
  switch(number) {
    case 0:
      return 'SUN';
      break;
    case 1:
      return 'MON';
      break;
    case 2:
      return 'TUE';
      break;
    case 3:
      return 'WED';
      break;
    case 4:
      return 'THU';
      break;
    case 5:
      return 'FRI';
      break;
    case 6:
      return 'SAT';
      break;
  }
}

/*---------------zjx---------------------*/

DlmanageUtils.stage = function(order) {
  var received1 = 0, cash1 = 0, received2 = 0, cash2 = 0, received3 = 0, cash3 = 0, received4 = 0, cash4 = 0, receipt = 0;
  var date1 = [], date2 = [], date3 = [], date4 = [];
  MiscUtils.sort(order.payments, ['id']);
  for (var i = 0, il = order.payments.length; i < il; i++) {
    var payment = order.payments[i];
    if (payment.cancelled == 1) {
      continue;
    }
    receipt += parseFloat(payment.amount);
    
    if (payment.stage == 1) {
      date1[date1.length] = payment.date;
      received1 += parseFloat(payment.amount);
      if (payment.method == 'cash') {
        cash1 += parseFloat(payment.amount);
      }
    } else if (payment.stage == 2) {
      date2[date2.length] = payment.date;
      received2 += parseFloat(payment.amount);
      if (payment.method == 'cash') {
        cash2 += parseFloat(payment.amount);
      }
    } else if (payment.stage == 3) {
      date3[date3.length] = payment.date;
      received3 += parseFloat(payment.amount);
      if (payment.method == 'cash') {
        cash3 += parseFloat(payment.amount);
      }
    } else {
      date4[date4.length] = payment.date;
      received4 += parseFloat(payment.amount);
      if (payment.method == 'cash') {
        cash4 += parseFloat(payment.amount);
      }
    }
  }
  
  return { pay1: { date: date1,
                   cash: cash1,
                   nonCash: received1-cash1
                 },
           pay2: { date: date2,
                   cash: cash2,
                   nonCash: received2-cash2
                 },
           pay3: { date: date3,
                   cash: cash3,
                   nonCash: received3-cash3
                 },
           pay4: { date: date4,
                   cash: cash4,
                   nonCash: received4-cash4
                 },
           receipt: receipt
         }
};

DlmanageUtils.monthChange = function(month) {
  var x = '';
  if (month == '1') {
    x = 'JAN';
  } else if (month == '2') {
    x = 'FEB';
  } else if (month == '3') {
    x = 'MAR';
  } else if (month == '4') {
    x = 'APR';
  } else if (month == '5') {
    x = 'MAY';
  } else if (month == '6') {
    x = 'JUN';
  } else if (month == '7') {
    x = 'JUL';
  } else if (month == '8') {
    x = 'AUG';
  } else if (month == '9') {
    x = 'SEP';
  } else if (month == '10') {
    x = 'OCT';
  } else if (month == '11') {
    x = 'NOV';
  } else {
    x = 'DEC';
  }
  return x;
};

/*-06.03-*/
DlmanageUtils.convert = function(str) {
  var pp = 0;
  if (str.indexOf(',') > 0) {
    pp = str.indexOf(',');
  } else if(str.indexOf('.') > 0) {
    pp = str.indexOf('.');
  } else {
    pp = str.length - 1;
  }
  pp = pp - 3;
  if (pp <= 0) {
    return str;
  } else {
    var s = str.substring(0, pp);
    var e = str.substring(pp);
    var str1 = s + ((s == '-') ? '' : ',') + e;
    if (str1 == str) {
      return str1 ;
    }
    this.convert(str1);
    return str1;
  }
};

DlmanageUtils.isFirstAlbum = function(purchases, item) {
  var first = true;
  for (var i = 0, il = purchases.length; i < il; i++) {
    var purchase = purchases[i];
    if (purchase.cancelled == 1) {
      continue;
    }
    if (purchase.trackId != item.trackId && (purchase.type == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_ALBUM)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' || purchase.type == '<?php echo ((is_array($_tmp=@SAMPLE_TYPE_MAGAZINE)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
')) {
      first = false;
    }
  }
  return first;
};

/**
 * PackageItems的selects
 */
DlmanageUtils.packageSelects = function(item, sample) {
  var objects = [];
  for (var m = 0, ml = item.selects.length; m < ml; m++) {
    var sel = item.selects[m];
    var exist = false, exist1 = false;
    for (var n = 0, nl = sample.attributes.length; n < nl; n++) {
      var attribute = sample.attributes[n];
      if (sel.title == attribute.name) {
        exist1 = true;
      }
      if (exist1) {
        for (var k = 0, kl = objects.length; k < kl; k++) {
          var object = objects[k];
          if (object.title == sel.title) {
            exist = true;
          }
        }
        if (!exist) {
          objects[objects.length] = sel;
        }
      }
    }
  }
  item.selects = objects;
  return item;
};

DlmanageUtils.modifyAttr = function(old, sample, mattr, mopt, dattr, dopt) {
  for (var i = 0, il = old.attributes.length; i < il; i++) {
    var oldattr = old.attributes[i];
    for (var j = 0, jl = sample.attributes.length; j < jl; j++) {
      var newattr = sample.attributes[j];
      if (oldattr.e_oid == newattr.e_oid) {
        if (oldattr.name == newattr.name) {
          for (var m = 0, ml = oldattr.options.length; m < ml; m++) {
            var oldopt = oldattr.options[m];
            for (var n = 0, nl = newattr.options.length; n < nl; n++) {
              var newopt = newattr.options[n];
              if (oldopt.e_oid == newopt.e_oid) {
                if (oldopt.name != newopt.name) {
                  var mo = { attr: newattr.name,
                             old: oldopt.name,
                             new: newopt.name
                           };
                  mopt[mopt.length] = mo;
                }
              }
            }
          }
        } else {
          var ma = { old: oldattr.name,
                     new: newattr.name
                   };
          mattr[mattr.length] = ma;
          for (var m = 0, ml = oldattr.options.length; m < ml; m++) {
            var oldopt = oldattr.options[m];
            for (var n = 0, nl = newattr.options.length; n < nl; n++) {
              var newopt = newattr.options[n];
              if (oldopt.e_oid == newopt.e_oid) {
                if (oldopt.name != newopt.name) {
                  var mo = { attr: newattr.name,
                             old: oldopt.name,
                             new: newopt.name
                           };
                  mopt[mopt.length] = mo;
                }
              }
            }
          }
        }
      }
    }
  }
  
  for (var i = 0, il = old.attributes.length; i < il; i++) {
    var oldattr = old.attributes[i];
    var nonExist = false;
    for (var j = 0, jl = sample.attributes.length; j < jl; j++) {
      var newattr = sample.attributes[j];
      if (oldattr.e_oid == newattr.e_oid) {
        nonExist = true;
      }
    }
    if (!nonExist) {
      var ma = { old: oldattr.name };
      dattr[dattr.length] = ma;
    }
  }
  
  for (var a = 0, al = old.attributes.length; a < al; a++) {
    var oldattr = old.attributes[a];
    for (var b = 0, bl = sample.attributes.length; b < bl; b++) {
      var newattr = sample.attributes[b];
      if (oldattr.e_oid == newattr.e_oid) {
        for (var m = 0, ml = oldattr.options.length; m < ml; m++) {
          var oldopt = oldattr.options[m];
          var nonExist = false;
          for (var n = 0, nl = newattr.options.length; n < nl; n++) {
            var newopt = newattr.options[n];
            if (oldopt.e_oid == newopt.e_oid) {
              nonExist = true;
            }
          }
          if (!nonExist) {
            var delo = { attr: newattr.name,
                         old: oldopt.name
                       };
            dopt[dopt.length] = delo;
          }
        }
      }
    }
  }
};

DlmanageUtils.modifyAttr1 = function(old, sample, mattr, mopt, dattr, dopt) {
  for (var i = 0, il = sample.attributes.length; i < il; i++) {
    var newattr = sample.attributes[i];
    for (var n = 0, nl = newattr.options.length; n < nl; n++) {
      var newopt = newattr.options[n];
      var mo = { attr: newattr.name,
                 old: '',
                 new: newopt.name
               };
      mopt[mopt.length] = mo;
    }
  }
};

DlmanageUtils.modifySelects = function(selects, mattrs, mopts, dattrs, dopts) {
  
  for (var b = 0, bl = selects.length; b < bl; b++) {
    var sel = selects[b];
    for (var c = 0, cl = mattrs.length; c < cl; c++) {
      var mattr = mattrs[c];
      if (sel.title == mattr.old) {
        sel.title = mattr.new;
      }
    }
  }
  
  for (var d = 0, dl = selects.length; d < dl; d++) {
    var sel = selects[d];
    for (var e = 0, el = mopts.length; e < el; e++) {
      var mopt = mopts[e];
      if (sel.title == mopt.attr && sel.value == mopt.old) {
        sel.value = mopt.new;
      }
    }
  }
  
  var objects = [];
  for (var f = 0, fl = selects.length; f < fl; f++) {
    var sel = selects[f];
    for (var g = 0, gl = dattrs.length; g < gl; g++) {
      var dattr = dattrs[g];
      if (sel.title == dattr.old) {
        objects[objects.length] = sel;
      }
    }
  }
  
  for (var j = 0, jl = objects.length; j < jl; j++) {
    var object = objects[j];
    MiscUtils.remove(selects, object, 'trackId');
  }
  
  for (var h = 0, hl = selects.length; h < hl; h++) {
    var sel = selects[h];
    for (var i = 0, il = dopts.length; i < il; i++) {
      var dopt = dopts[i];
      if (sel.title == dopt.attr && sel.value == dopt.old) {
        sel.value = '';
      }
    }
  }
};

DlmanageUtils.modelCheck = function(orders) {
  for (var i = 0, il = orders.length; i < il; i++) {
    var order = orders[i];
    var count = 0; count1 = 0;
    for (var j = 0, jl = order.purchaseItems.length; j < jl; j++) {
      var pur = order.purchaseItems[j];
      if (pur.model == '<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_VIDEO)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' && pur.cancelled == 0) {
        count++;
      }
      if (pur.model == '<?php echo ((is_array($_tmp=@MODEL_NAME_PRODUCT_VIDEO_BLURAY)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
' && pur.cancelled == 0) {
        count1++;
      }
    }
    if (count > 1 || count1 > 1) {
      return true;
    }
  }
  return false;
};

DlmanageUtils.checkOrderDate = function(orders) {
  var str = '';
  for (var i = 0, il = orders.length; i <il; i++) {
    var order = orders[i];
    if (!order.date) {
      if (order.type != '<?php echo ((is_array($_tmp=@ORDER_TYPE_ENGAGEMENT)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
') {
        str += (order.flag + ', ');
      }
    }
  }
  return str;
};


/*
 *send email
 *2011年11月8日 10:39:20
 *
 */
 DlmanageUtils.sendEmail = function(uemail,pos,func,callbackFunc,user) {
 
                                   switch(uemail.pi_model)
                                   {
                                      case 'Photographer':
                                      var otype = 'photography';
                                      break;
                                      
                                      case 'Videographer':
                                      var otype = 'cinematography';
                                      break;
                                      
                                      case 'Makeup':
                                      var otype = 'Makeup';
                                      break;

                                      case 'Lighting Assistant':
                                      var otype = 'Lighting Assistant';
                                      break; 
                                      
                                      default:
                                      var otype = 'photography';  
                                      break;                                   
                                      
                                   }

                                    switch(uemail.state)
                                   { 
                                        
                                      case '1':
                                      {
                                      var content = "Dear "+uemail.user_name +"," + "\n"+
                                                      "\n" +
                                                     "Please confirm by email or telephone your availability for a "+ otype +
                                                     " assignment on the  "+ SimpleDate.format(uemail.date) +" ."+
                                                     "Your response is needed within 72 hours of your receipt of this email to avoid reassignment of the said job. " + 
                                                     "\n" +
                                                     "Please note that this is a system generated email and that you should direct all correspondence to "+
                                                     '<?php echo ((is_array($_tmp=@MANAGE_EMAILADD)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'+" or " +'<?php echo ((is_array($_tmp=@MANAGE_TEL)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'+ ".\n"+
                                                     "\n" +
                                                     "By expressed or implied acceptance of the contracted jobs listed in this email, you agree to be liable for any direct or indirect damages or "+
                                                      "losses suffered by New York Photos & Video, arising from your withdrawal, in part or in full. New York Photos & Video may at its sole discretion, waive your "+
                                                      "responsibility to the above stated withdrawals."+"\n"+
                                                      "\n" +
                                                      "\n" +
                                                     "Yours sincerely,"+ "\n"+
                                                     ""+user.name;
                                          var  usubject = uemail.pi_model=='Makeup'? 'arrange' : 'select';        
                                                    
                                        }
                                         break;        
                                                     
                                       case'2':
                                       {              
                                       var content = "Dear "+uemail.user_name +"," + "\n"+
                                                      "\n" +
                                                     "Thank you for making yourself available on the  "+ SimpleDate.format(uemail.date) +" ." +
                                                     "We will get in touch with you regarding the pre-wedding consultation session and other details in due course." +
                                                     "\n" +
                                                     "Please note that this is a system generated email and that you should direct all correspondence to  "+
                                                     '<?php echo ((is_array($_tmp=@MANAGE_EMAILADD)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'+" or " +'<?php echo ((is_array($_tmp=@MANAGE_TEL)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'+ ".\n"+
                                                     "\n" +
                                                      "\n" +
                                                     "Yours sincerely,"+ "\n"+
                                                     ""+user.name;   
                                        var  usubject = 'confirmed';                                                 
                                                      
                                        }
                                        break; 
                                                
                                        case'3':
                                        {             
                                        var content = "Dear "+uemail.user_name +"," + "\n"+
                                                      "\n" +
                                                     "Please be reminded that you have a "+ otype +" assignment coming up on the  "+ SimpleDate.format(uemail.date) +" ." +
                                                     "Should you be in need of any assistance please contact us directly at  "+ '<?php echo ((is_array($_tmp=@MANAGE_TEL)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'+".\n" +
                                                     "\n" +
                                                     "Please note that this is a system generated email and that you should direct all correspondence to "+
                                                     '<?php echo ((is_array($_tmp=@MANAGE_EMAILADD)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'+" or " +'<?php echo ((is_array($_tmp=@MANAGE_TEL)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
'+ ".\n"+
                                                     "\n" +
                                                      "\n" +
                                                     "Yours sincerely,"+ "\n"+
                                                     ""+user.name; 
                                          var  usubject = 'reminded';           
                                         }      
                                         
                                         break;  
                                         
                                         default:
                                         var content = '';
                                         break;                                                         
                                      }

                                   var  func11, func21,noemail = 0;
                                   var enote = [];
                                   _popupBox2 = new PopupBox2()
                                   var div1 = document.createElement('div');
                                   var div2 = document.createElement('div');
                                   var div3 = document.createElement('div');
                                   var div4 = document.createElement('div');
                                   div2.style.paddingLeft = '30px'; 
                                   div2.style.marginTop = '5px';
                                   div3.style.marginTop = '5px';
                                   
                                   var checkbox = document.createElement('input');
                                       checkbox.type='checkbox';
                                 
                                 checkbox.onchange = function(){
                                                              if(this.checked)
                                                              {
                                                                input.disabled = true;
                                                                input1.disabled = true;
                                                                enote.disabled = true;
                                                                noemail = 1; 
                                                              }else{
                                                                input.disabled = false;
                                                                input1.disabled = false;
                                                                enote.disabled = false;
                                                                noemail = 0;
                                                              }
                                                             };
                                     
                                   var input = document.createElement('input');
                                       input.type='text';
                                       input.style.width = '435px'
                                       input.value = uemail.user_email;
                                   
                                     
                                   var input1 = document.createElement('input');
                                       input1.type='text';
                                       input1.style.width = '435px'
                                       input1.value = usubject +' '+ uemail.pi_model;
                                       
                                      div4.appendChild(checkbox);
                                      div4.appendChild(document.createTextNode('NO EMAIL NEEDED'));
                                      div2.appendChild(document.createTextNode('To: '));
                                      div2.appendChild(input);
                                      div3.appendChild(document.createTextNode('Subject: '));
                                      div3.appendChild(input1);
                                      
                                      div1.appendChild(div4);
                                      div1.appendChild(div2);
                                      div1.appendChild(div3);
                                      

                                   
                                   func11 = function() { 
                                                         var email ={};
                                                         email.noemail = noemail;
                                                         email.to = input.value;
                                                         email.subject = input1.value;
                                                         email.comment = enote._text;
                                                         
                                                        
                                                         new RequestUtils()._mwrite('sendemail',[email], [], func, { pos: pos });
                                                        _popupBox2._close();
                                                      };
                                   var func21 = function() { _popupBox2._close();callbackFunc(); };
                                   MiscUtils.dialog(_popupBox2, pos, div1, func11, func21, {t: 'Send Email'});
                                   new DialogInput(div1,enote, { title: '', default: content });
 };
 
DlmanageUtils.trimcustomer = function(customer) {
   var cus = customer;
   cus.bridemobile = cus.bridemobile==''? cus.bridemobile : MiscUtils.Trim(cus.bridemobile,'g') ;
   cus.bridephone = cus.bridephone==''? cus.bridephone : MiscUtils.Trim(cus.bridephone,'g');
   cus.groommobile = cus.groommobile==''? cus.groommobile : MiscUtils.Trim(cus.groommobile,'g');
   cus.groomphone = cus.groomphone==''? cus.groomphone : MiscUtils.Trim(cus.groomphone,'g');
   
   return customer;
}; 

/**
 * 订单日期
 */

DlmanageUtils.orderdate = function(arr,orders) {
  var str='';
  
   for(var j=0;ij=orders.length,j<ij; j++)
   {
     var  a1 =[],wdstr='';
     var order = orders[j];
   
   
       for(var i=0;il=arr.length,i<il;i++)
       {
           var warr = arr[i];
           if(warr.indexOf(order.flag)>=0)
           {
             a1.push(warr);
           }
       }
       
       if(order.type != '<?php echo ((is_array($_tmp=@ORDER_TYPE_WEDDING)) ? $this->_run_mod_handler('escape', true, $_tmp, 'javascript') : smarty_modifier_escape($_tmp, 'javascript')); ?>
')
       {
         wdstr ="Working Date";
       }else{
         wdstr ="Wedding Date";
       }
       
       if(a1.length>0)
       {
           if(a1[0] != a1[a1.length-1])
           {
             str += order.flag +': '+wdstr +' Has been changed!( '+a1[0]+'->'+ a1[a1.length-1]+')'+"\n";
           }
       }
   
   }
   return str;
   
};

 